📄 httpurlconnection.java
字号:
/* HTTPURLConnection.java -- Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version. GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING. If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library. Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule. An independent module is a module which is not derived fromor based on this library. If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so. If you do not wish to do so, delete thisexception statement from your version. */package gnu.java.net.protocol.http;import java.io.ByteArrayOutputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ProtocolException;import java.net.URL;import java.security.AccessController;import java.security.PrivilegedAction;import java.security.cert.Certificate;import java.util.Collections;import java.util.Date;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import javax.net.ssl.HandshakeCompletedEvent;import javax.net.ssl.HandshakeCompletedListener;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLPeerUnverifiedException;import javax.net.ssl.SSLSocketFactory;/** * A URLConnection that uses the HTTPConnection class. * * @author Chris Burdess (dog@gnu.org) */public class HTTPURLConnection extends HttpsURLConnection implements HandshakeCompletedListener{ /** * Pool of reusable connections, used if keepAlive is true. */ private static final LinkedHashMap connectionPool = new LinkedHashMap(); static int maxConnections; /* * The underlying connection. */ private HTTPConnection connection; // These are package private for use in anonymous inner classes. String proxyHostname; int proxyPort; String agent; boolean keepAlive; private Request request; private Headers requestHeaders; private ByteArrayOutputStream requestSink; private boolean requestMethodSetExplicitly; private Response response; private InputStream responseSink; private InputStream errorSink; private HandshakeCompletedEvent handshakeEvent; /** * Constructor. * @param url the URL */ public HTTPURLConnection(URL url) throws IOException { super(url); requestHeaders = new Headers(); AccessController.doPrivileged(this.new GetHTTPPropertiesAction()); } class GetHTTPPropertiesAction implements PrivilegedAction { public Object run() { proxyHostname = System.getProperty("http.proxyHost"); if (proxyHostname != null && proxyHostname.length() > 0) { String port = System.getProperty("http.proxyPort"); if (port != null && port.length() > 0) { proxyPort = Integer.parseInt(port); } else { proxyHostname = null; proxyPort = -1; } } agent = System.getProperty("http.agent"); String ka = System.getProperty("http.keepAlive"); keepAlive = !(ka != null && "false".equals(ka)); String mc = System.getProperty("http.maxConnections"); maxConnections = (mc != null && mc.length() > 0) ? Math.max(Integer.parseInt(mc), 1) : 5; return null; } } public void connect() throws IOException { if (connected) { return; } String protocol = url.getProtocol(); boolean secure = "https".equals(protocol); String host = url.getHost(); int port = url.getPort(); if (port < 0) { port = secure ? HTTPConnection.HTTPS_PORT : HTTPConnection.HTTP_PORT; } String file = url.getFile(); String username = url.getUserInfo(); String password = null; if (username != null) { int ci = username.indexOf(':'); if (ci != -1) { password = username.substring(ci + 1); username = username.substring(0, ci); } } final Credentials creds = (username == null) ? null : new Credentials (username, password); boolean retry; do { retry = false; if (connection == null) { connection = getConnection(host, port, secure); if (secure) { SSLSocketFactory factory = getSSLSocketFactory(); HostnameVerifier verifier = getHostnameVerifier(); if (factory != null) { connection.setSSLSocketFactory(factory); } connection.addHandshakeCompletedListener(this); // TODO verifier } } if (proxyHostname != null) { if (proxyPort < 0) { proxyPort = secure ? HTTPConnection.HTTPS_PORT : HTTPConnection.HTTP_PORT; } connection.setProxy(proxyHostname, proxyPort); } try { request = connection.newRequest(method, file); if (!keepAlive) { request.setHeader("Connection", "close"); } if (agent != null) { request.setHeader("User-Agent", agent); } request.getHeaders().putAll(requestHeaders); if (requestSink != null) { byte[] content = requestSink.toByteArray(); RequestBodyWriter writer = new ByteArrayRequestBodyWriter(content); request.setRequestBodyWriter(writer); } if (creds != null) { request.setAuthenticator(new Authenticator() { public Credentials getCredentials(String realm, int attempts) { return (attempts < 2) ? creds : null; } }); } response = request.dispatch(); } catch (IOException ioe) { if (connection.useCount > 0) { // Connection re-use failed: Try a new connection. try { connection.close(); } catch (IOException _) { // Ignore. } connection = null; retry = true; continue; } else { // First time the connection was used: Hard failure. throw ioe; } } if (isRedirect(response) && getInstanceFollowRedirects()) { // Read the response body, if there is one. If the // redirect points us back at the same server, we will use // the cached connection, so we must make sure there is no // pending data in it. InputStream body = response.getBody(); if (body != null) { byte[] ignore = new byte[1024]; while (true) { int n = body.read(ignore, 0, ignore.length); if (n == -1) break; } } // Follow redirect String location = response.getHeader("Location"); if (location != null) { String connectionUri = connection.getURI(); int start = connectionUri.length(); if (location.startsWith(connectionUri) && location.charAt(start) == '/') { file = location.substring(start); retry = true; } else if (location.startsWith("http:")) { connection.close(); connection = null; secure = false; start = 7; int end = location.indexOf('/', start); host = location.substring(start, end); int ci = host.lastIndexOf(':'); if (ci != -1) { port = Integer.parseInt(host.substring (ci + 1)); host = host.substring(0, ci); } else { port = HTTPConnection.HTTP_PORT; } file = location.substring(end); retry = true; } else if (location.startsWith("https:")) { connection.close(); connection = null; secure = true; start = 8; int end = location.indexOf('/', start); host = location.substring(start, end); int ci = host.lastIndexOf(':'); if (ci != -1) { port = Integer.parseInt(host.substring (ci + 1)); host = host.substring(0, ci); } else { port = HTTPConnection.HTTPS_PORT; } file = location.substring(end); retry = true; } else if (location.length() > 0) { // Malformed absolute URI, treat as file part of URI if (location.charAt(0) == '/') { // Absolute path file = location; } else { // Relative path int lsi = file.lastIndexOf('/'); file = (lsi == -1) ? "/" : file.substring(0, lsi + 1); file += location; } retry = true; } } } else { responseSink = response.getBody(); if (response.getCode() == 404) { errorSink = responseSink; throw new FileNotFoundException(url.toString()); } } } while (retry); connected = true; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -