httpurlconnection.java

来自「纯java操作系统jnode,安装简单和操作简单的个人使用的Java操作系统」· Java 代码 · 共 577 行 · 第 1/2 页

JAVA
577
字号
  /**
   * This is a list of valid request methods, separated by "|" characters.
   */
  private static String valid_methods
      = "|GET|POST|HEAD|OPTIONS|PUT|DELETE|TRACE|";

  // Instance Variables

  /**
   * The requested method in use for this connection. Default is GET.
   */
  protected String method = "GET";

  /**
   * The response code received from the server
   */
  protected int responseCode = -1;

  /**
   * The response message string received from the server.
   */
  protected String responseMessage = null;

  /**
   * If this instance should follow redirect requests.
   */
  protected boolean instanceFollowRedirects = followRedirects;

  /**
   * Whether we alreadt got a valid response code for this connection.
   * Used by <code>getResponceCode()</code> and
   * <code>getResponseMessage()</code>.
   */
  private boolean gotResponseVals = false;

  /**
   * Create an HttpURLConnection for the specified URL
   *
   * @param url The URL to create this connection for.
   */
  protected HttpURLConnection(URL url)
  {
    super(url);
  }
  
  /**   
   * Closes the connection to the server.
   */
  public abstract void disconnect();

  /** 
   * Returns a boolean indicating whether or not this connection is going
   * through a proxy
   * 
   * @return true if through a proxy, false otherwise
   */
  public abstract boolean usingProxy();

  /**
   * Sets whether HTTP redirects (requests with response code 3xx) should be
   * automatically followed by this class. True by default
   *
   * @param set true if redirects should be followed, false otherwis.
   *
   * @exception SecurityException If a security manager exists and its
   * checkSetFactory method doesn't allow the operation
   */
  public static void setFollowRedirects(boolean set)
  {
    // Throw an exception if an extant security mgr precludes
    // setting the factory.
    SecurityManager s = System.getSecurityManager();
    if (s != null)
      s.checkSetFactory();

    followRedirects = set;
  }

  /**
   * Returns a boolean indicating whether or not HTTP redirects will 
   * automatically be followed or not.
   *
   * @return true if redirects will be followed, false otherwise
   */
  public static boolean getFollowRedirects()
  {
    return followRedirects;
  }

  /**
   * Returns the value of this HttpURLConnection's instanceFollowRedirects
   * field
   */
  public boolean getInstanceFollowRedirects ()
  {
    return instanceFollowRedirects;
  }

  /**
   * Sets the value of this HttpURLConnection's instanceFollowRedirects field
   */
  public void setInstanceFollowRedirects (boolean follow)
  {
    instanceFollowRedirects = follow;
  }

  /**
   * Set the method for the URL request, one of:
   * GET POST HEAD OPTIONS PUT DELETE TRACE are legal
   *
   * @exception ProtocolException If the method cannot be reset or if the
   * requested method isn't valid for HTTP
   */
  public void setRequestMethod(String method) throws ProtocolException
  {
    if (connected)
      throw new ProtocolException("Already connected");

    method = method.toUpperCase();
    if (valid_methods.indexOf("|" + method + "|") != -1)
      this.method = method;
    else
      throw new ProtocolException("Invalid HTTP request method: " + method);

  }

  /**
   * The request method currently in use for this connection.
   *
   * @return The request method
   */
  public String getRequestMethod()
  {
    return method;
  }

  /**
   * Gets the status code from an HTTP response message, or -1 if
   * the response code could not be determined.
   * Note that all valid response codes have class variables
   * defined for them in this class.
   *
   * @return The response code
   *
   * @exception IOException If an error occurs
   */
  public int getResponseCode() throws IOException
  {
    if (!gotResponseVals)
      getResponseVals();
    return responseCode;
  }

  /**
   * Gets the HTTP response message, if any, returned along with the
   * response code from a server. Null if no response message was set
   * or an error occured while connecting.
   *
   * @return The response message
   *
   * @exception IOException If an error occurs
   */
  public String getResponseMessage() throws IOException
  {
    if (!gotResponseVals)
      getResponseVals();
    return responseMessage;
  }

  private void getResponseVals() throws IOException
  {
    // getHeaderField() will connect for us, but do it here first in
    // order to pick up IOExceptions.
    if (!connected)
      connect();
      
    gotResponseVals = true;

    // If responseCode not yet explicitly set by subclass
    if (responseCode == -1)
      {
	// Response is the first header received from the connection.
	String respField = getHeaderField(0);
	
	if (respField == null || ! respField.startsWith("HTTP/"))
	  {
	    // Set to default values on failure.
	    responseCode = -1;
	    responseMessage = null;
	    return;
	  }

	int firstSpc, nextSpc;
	firstSpc = respField.indexOf(' ');
	nextSpc = respField.indexOf(' ', firstSpc + 1);
	responseMessage = respField.substring(nextSpc + 1);
	String codeStr = respField.substring(firstSpc + 1, nextSpc);
	try
	  {
	    responseCode = Integer.parseInt(codeStr);
	  }
	catch (NumberFormatException e)
	  {
	    // Set to default values on failure.
	    responseCode = -1;
	    responseMessage = null;
	  }
      }
  }

  /**
   * Returns a permission object representing the permission necessary to make
   * the connection represented by this object
   *
   * @exception IOException If an error occurs
   */
  public Permission getPermission() throws IOException
  {
    URL url = getURL();
    String host = url.getHost();
    int port = url.getPort();
    if (port == -1)
      port = 80;
    
    host = host + ":" + port;
    
    return new SocketPermission(host, "connect");
  }

  /**
   * This method allows the caller to retrieve any data that might have
   * been sent despite the fact that an error occurred.  For example, the
   * HTML page sent along with a 404 File Not Found error.  If the socket
   * is not connected, or if no error occurred or no data was returned,
   * this method returns <code>null</code>.
   *
   * @return An <code>InputStream</code> for reading error data.
   */
  public InputStream getErrorStream ()
  {
    if (!connected)
      return(null);
    
    int code;
    try 
      {
	code = getResponseCode();
      }
    catch(IOException e)
      {
	code = -1;
      }
    
    if (code == -1)
      return(null);
    
    if (((code/100) != 4) || ((code/100) != 5))
      return(null); 
    
    try
      {
	PushbackInputStream pbis = new PushbackInputStream(getInputStream());
	
	int i = pbis.read();
	if (i == -1)
	  return(null);
	
	pbis.unread(i);
	return(pbis);
      }
    catch(IOException e)
      {
	return(null);
      }
  }

  /**
   * Returns the value of the named field parsed as date
   */
  public long getHeaderFieldDate (String key, long value)
  {
    // FIXME: implement this correctly
    // http://www.w3.org/Protocols/HTTP-NG/ng-notes.txt
    
    return super.getHeaderFieldDate (key, value);
  }
}

⌨️ 快捷键说明

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