httpurlconnection.java

来自「Mac OS X 10.4.9 for x86 Source Code gcc」· Java 代码 · 共 650 行 · 第 1/2 页

JAVA
650
字号
/* HTTPURLConnection.java --   Copyright (C) 2004 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., 59 Temple Place, Suite 330, Boston, MA02111-1307 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.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.IOException;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.Date;import java.util.Collections;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 Map connectionPool = new LinkedHashMap();  /*   * The underlying connection.   */  private HTTPConnection connection;  private String proxyHostname;  private int proxyPort;  private String agent;  private boolean keepAlive;  private int maxConnections;  private Request request;  private Headers requestHeaders;  private ByteArrayOutputStream requestSink;  private boolean requestMethodSetExplicitly;  private Response response;  private ByteArrayInputStream responseSink;  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);          }        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);          }        ByteArrayResponseBodyReader reader = new ByteArrayResponseBodyReader();        request.setResponseBodyReader(reader);        if (creds != null)          {            request.setAuthenticator(new Authenticator() {              public Credentials getCredentials(String realm, int attempts)              {                return (attempts < 2) ? creds : null;              }            });          }        response = request.dispatch();        if (response.getCodeClass() == 3 && getInstanceFollowRedirects())          {            // Follow redirect            String location = response.getHeader("Location");            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;              }            // Otherwise this is not an HTTP redirect, can't follow          }        else          {            responseSink = new ByteArrayInputStream(reader.toByteArray ());          }      }    while (retry);    connected = true;  }  /**   * Returns a connection, from the pool if necessary.   */  HTTPConnection getConnection(String host, int port, boolean secure)    throws IOException  {    HTTPConnection connection;    if (keepAlive)      {        StringBuffer buf = new StringBuffer(secure ? "https://" : "http://");        buf.append(host);        buf.append(':');        buf.append(port);        String key = buf.toString();        synchronized (connectionPool)          {            connection = (HTTPConnection) connectionPool.get(key);            if (connection == null)              {                connection = new HTTPConnection(host, port, secure);                // Good housekeeping                if (connectionPool.size() == maxConnections)                  {                    // maxConnections must always be >= 1                    Object lru = connectionPool.keySet().iterator().next();                    connectionPool.remove(lru);                  }                connectionPool.put(key, connection);              }          }      }    else

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?