httpconnection.java

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

JAVA
700
字号
  /**   * Creates a new request using this connection.   * @param method the HTTP method to invoke   * @param path the URI-escaped RFC2396 <code>abs_path</code> with   * optional query part   */  public Request newRequest(String method, String path)  {    if (method == null || method.length() == 0)      {        throw new IllegalArgumentException("method must have non-zero length");      }    if (path == null || path.length() == 0)      {        path = "/";      }    Request ret = new Request(this, method, path);    if ((secure && port != HTTPS_PORT) ||        (!secure && port != HTTP_PORT))      {        ret.setHeader("Host", hostname + ":" + port);      }    else      {        ret.setHeader("Host", hostname);      }    ret.setHeader("User-Agent", userAgent);    ret.setHeader("Connection", "keep-alive");    ret.setHeader("Accept-Encoding",                  "chunked;q=1.0, gzip;q=0.9, deflate;q=0.8, " +                  "identity;q=0.6, *;q=0");    if (cookieManager != null)      {        Cookie[] cookies = cookieManager.getCookies(hostname, secure, path);        if (cookies != null && cookies.length > 0)          {            StringBuffer buf = new StringBuffer();            buf.append("$Version=1");            for (int i = 0; i < cookies.length; i++)              {                buf.append(',');                buf.append(' ');                buf.append(cookies[i].toString());              }            ret.setHeader("Cookie", buf.toString());          }      }    fireRequestEvent(RequestEvent.REQUEST_CREATED, ret);    return ret;  }  /**   * Closes this connection.   */  public void close()    throws IOException  {    try      {        closeConnection();      }    finally      {        fireConnectionEvent(ConnectionEvent.CONNECTION_CLOSED);      }  }  /**   * Retrieves the socket associated with this connection.   * This creates the socket if necessary.   */  protected Socket getSocket()    throws IOException  {    if (socket == null)      {        String connectHostname = hostname;        int connectPort = port;        if (isUsingProxy())          {            connectHostname = proxyHostname;            connectPort = proxyPort;          }        socket = new Socket();        InetSocketAddress address =          new InetSocketAddress(connectHostname, connectPort);        if (connectionTimeout > 0)          {            socket.connect(address, connectionTimeout);          }        else          {            socket.connect(address);          }        if (timeout > 0)          {            socket.setSoTimeout(timeout);          }        if (secure)          {            try              {                SSLSocketFactory factory = getSSLSocketFactory();                SSLSocket ss =                  (SSLSocket) factory.createSocket(socket, connectHostname,                                                   connectPort, true);                String[] protocols = { "TLSv1", "SSLv3" };                ss.setEnabledProtocols(protocols);                ss.setUseClientMode(true);                synchronized (handshakeCompletedListeners)                  {                    if (!handshakeCompletedListeners.isEmpty())                      {                        for (Iterator i =                             handshakeCompletedListeners.iterator();                             i.hasNext(); )                          {                            HandshakeCompletedListener l =                              (HandshakeCompletedListener) i.next();                            ss.addHandshakeCompletedListener(l);                          }                      }                  }                ss.startHandshake();                socket = ss;              }            catch (GeneralSecurityException e)              {                throw new IOException(e.getMessage());              }          }        in = socket.getInputStream();        in = new BufferedInputStream(in);        out = socket.getOutputStream();        out = new BufferedOutputStream(out);      }    return socket;  }  SSLSocketFactory getSSLSocketFactory()    throws GeneralSecurityException  {    if (sslSocketFactory == null)      {        TrustManager tm = new EmptyX509TrustManager();        SSLContext context = SSLContext.getInstance("SSL");        TrustManager[] trust = new TrustManager[] { tm };        context.init(null, trust, null);        sslSocketFactory = context.getSocketFactory();      }    return sslSocketFactory;  }  void setSSLSocketFactory(SSLSocketFactory factory)  {    sslSocketFactory = factory;  }  protected InputStream getInputStream()    throws IOException  {    if (socket == null)      {        getSocket();      }    return in;  }  protected OutputStream getOutputStream()    throws IOException  {    if (socket == null)      {        getSocket();      }    return out;  }  /**   * Closes the underlying socket, if any.   */  protected void closeConnection()    throws IOException  {    if (socket != null)      {        try          {            socket.close();          }        finally          {            socket = null;          }      }  }  /**   * Returns a URI representing the connection.   * This does not include any request path component.   */  protected String getURI()  {    StringBuffer buf = new StringBuffer();    buf.append(secure ? "https://" : "http://");    buf.append(hostname);    if (secure)      {        if (port != HTTPConnection.HTTPS_PORT)          {            buf.append(':');            buf.append(port);          }      }    else      {        if (port != HTTPConnection.HTTP_PORT)          {            buf.append(':');            buf.append(port);          }      }    return buf.toString();  }  /**   * Get the number of times the specified nonce has been seen by this   * connection.   */  int getNonceCount(String nonce)  {    if (nonceCounts == null)      {        return 0;      }    return((Integer) nonceCounts.get(nonce)).intValue();  }  /**   * Increment the number of times the specified nonce has been seen.   */  void incrementNonce(String nonce)  {    int current = getNonceCount(nonce);    if (nonceCounts == null)      {        nonceCounts = new HashMap();      }    nonceCounts.put(nonce, new Integer(current + 1));  }  // -- Events --    public void addConnectionListener(ConnectionListener l)  {    synchronized (connectionListeners)      {        connectionListeners.add(l);      }  }  public void removeConnectionListener(ConnectionListener l)  {    synchronized (connectionListeners)      {        connectionListeners.remove(l);      }  }  protected void fireConnectionEvent(int type)  {    ConnectionEvent event = new ConnectionEvent(this, type);    ConnectionListener[] l = null;    synchronized (connectionListeners)      {        l = new ConnectionListener[connectionListeners.size()];        connectionListeners.toArray(l);      }    for (int i = 0; i < l.length; i++)      {        switch (type)          {          case ConnectionEvent.CONNECTION_CLOSED:            l[i].connectionClosed(event);            break;          }      }  }  public void addRequestListener(RequestListener l)  {    synchronized (requestListeners)      {        requestListeners.add(l);      }  }  public void removeRequestListener(RequestListener l)  {    synchronized (requestListeners)      {        requestListeners.remove(l);      }  }  protected void fireRequestEvent(int type, Request request)  {    RequestEvent event = new RequestEvent(this, type, request);    RequestListener[] l = null;    synchronized (requestListeners)      {        l = new RequestListener[requestListeners.size()];        requestListeners.toArray(l);      }    for (int i = 0; i < l.length; i++)      {        switch (type)          {          case RequestEvent.REQUEST_CREATED:            l[i].requestCreated(event);            break;          case RequestEvent.REQUEST_SENDING:            l[i].requestSent(event);            break;          case RequestEvent.REQUEST_SENT:            l[i].requestSent(event);            break;          }      }  }  void addHandshakeCompletedListener(HandshakeCompletedListener l)  {    synchronized (handshakeCompletedListeners)      {        handshakeCompletedListeners.add(l);      }  }  void removeHandshakeCompletedListener(HandshakeCompletedListener l)  {    synchronized (handshakeCompletedListeners)      {        handshakeCompletedListeners.remove(l);      }  }}

⌨️ 快捷键说明

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