HttpURLConnection.java 15.2 KB
Newer Older
Tom Tromey committed
1 2 3
// HttpURLConnection.java - Subclass of communications links using
//			Hypertext Transfer Protocol.

4
/* Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation
Tom Tromey committed
5

6
This file is part of GNU Classpath.
Tom Tromey committed
7

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the 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, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. 

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
39 40 41 42

package java.net;

import java.io.*;
43
import java.security.Permission;
Tom Tromey committed
44

45
/*
Tom Tromey committed
46 47 48 49 50
 * Written using on-line Java Platform 1.2 API Specification, as well
 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
 * Status:  Believed complete and correct.
 */

51 52 53 54 55 56 57 58 59 60 61 62 63
/**
 * This class provides a common abstract implementation for those 
 * URL connection classes that will connect using the HTTP protocol.
 * In addition to the functionality provided by the URLConnection
 * class, it defines constants for HTTP return code values and
 * methods for setting the HTTP request method and determining whether
 * or not to follow redirects. 
 *
 * @since 1.1
 *
 * @author Warren Levy (warrenl@cygnus.com)
 * @author Aaron M. Renn (arenn@urbanophile.com)
 */
Tom Tromey committed
64 65 66
public abstract class HttpURLConnection extends URLConnection
{
  /* HTTP Success Response Codes */
67 68 69 70 71 72 73 74 75 76 77

  /**
   * Indicates that the client may continue with its request.  This value
   * is specified as part of RFC 2068 but was not included in Sun's JDK, so
   * beware of using this value
   */
  static final int HTTP_CONTINUE = 100;
  
  /**
   * Indicates the request succeeded.
   */
Tom Tromey committed
78
  public static final int HTTP_OK		= 200;
79 80 81 82

  /**
   * The requested resource has been created.
   */
Tom Tromey committed
83
  public static final int HTTP_CREATED		= 201;
84 85 86 87 88 89

  /**
   * The request has been accepted for processing but has not completed.
   * There is no guarantee that the requested action will actually ever
   * be completed succesfully, but everything is ok so far.
   */
Tom Tromey committed
90
  public static final int HTTP_ACCEPTED 	= 202;
91 92 93 94 95 96

  /**
   * The meta-information returned in the header is not the actual data
   * from the original server, but may be from a local or other copy. 
   * Normally this still indicates a successful completion.
   */
Tom Tromey committed
97
  public static final int HTTP_NOT_AUTHORITATIVE = 203;
98 99 100 101 102

  /**
   * The server performed the request, but there is no data to send
   * back.  This indicates that the user's display should not be changed.
   */
Tom Tromey committed
103
  public static final int HTTP_NO_CONTENT	= 204;
104 105 106 107 108 109

  /**
   * The server performed the request, but there is no data to sent back,
   * however, the user's display should be "reset" to clear out any form
   * fields entered.
   */
Tom Tromey committed
110
  public static final int HTTP_RESET		= 205;
111 112 113 114

  /**
   * The server completed the partial GET request for the resource.
   */
Tom Tromey committed
115 116
  public static final int HTTP_PARTIAL		= 206;

117

Tom Tromey committed
118 119
  /* HTTP Redirection Response Codes */

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  /**
   * There is a list of choices available for the requested resource.
   */
  public static final int HTTP_MULT_CHOICE = 300;
  
  /**
   * The resource has been permanently moved to a new location.
   */
  public static final int HTTP_MOVED_PERM = 301;
  
  /**
   * The resource requested has been temporarily moved to a new location.
   */
  public static final int HTTP_MOVED_TEMP = 302;
  
  /**
   * The response to the request issued is available at another location.
   */
  public static final int HTTP_SEE_OTHER = 303;
  
  /**
   * The document has not been modified since the criteria specified in
   * a conditional GET.
   */
  public static final int HTTP_NOT_MODIFIED = 304;
  
  
Tom Tromey committed
147
  /* HTTP Client Error Response Codes */
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

  /**
   * The request was misformed or could not be understood.
   */
  public static final int HTTP_BAD_REQUEST = 400;
  
  /**
   * The request made requires user authorization.  Try again with
   * a correct authentication header.
   */
  public static final int HTTP_UNAUTHORIZED = 401;
  
  /**
   * Code reserved for future use - I hope way in the future.
   */
  public static final int HTTP_PAYMENT_REQUIRED = 402;
  
  /**
   * There is no permission to access the requested resource.
   */
  public static final int HTTP_FORBIDDEN = 403;
  
  /**
   * The requested resource was not found.
   */
  public static final int HTTP_NOT_FOUND = 404;
  
  /**
   * The specified request method is not allowed for this resource.
   */
  public static final int HTTP_BAD_METHOD = 405;
  
  /**
   * Based on the input headers sent, the resource returned in response
   * to the request would not be acceptable to the client.
   */
  public static final int HTTP_NOT_ACCEPTABLE = 406;
  
  /**
   * The client must authenticate with a proxy prior to attempting this
   * request.
   */
  public static final int HTTP_PROXY_AUTH = 407;
  
  /**
   * The request timed out.
   */
  public static final int HTTP_CLIENT_TIMEOUT = 408;
  
  /**
   * There is a conflict between the current state of the resource and the
   * requested action.
   */
  public static final int HTTP_CONFLICT = 409;
  
  /**
   * The requested resource is no longer available.  This ususally indicates
   * a permanent condition.
   */
  public static final int HTTP_GONE = 410;

  /**
   * A Content-Length header is required for this request, but was not
   * supplied.
   */
  public static final int HTTP_LENGTH_REQUIRED = 411;
  
  /**
   * A client specified pre-condition was not met on the server.
   */
  public static final int HTTP_PRECON_FAILED = 412;
  
  /**
   * The request sent was too large for the server to handle.
   */
  public static final int HTTP_ENTITY_TOO_LARGE = 413;
  
  /**
   * The name of the resource specified was too long.
   */
  public static final int HTTP_REQ_TOO_LONG = 414;
  
  /**
   * The request is in a format not supported by the requested resource.
   */
  public static final int HTTP_UNSUPPORTED_TYPE = 415;

Tom Tromey committed
235 236 237

  /* HTTP Server Error Response Codes */

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  /**
   * This error code indicates that some sort of server error occurred.
   */
  public static final int HTTP_SERVER_ERROR    = 500;

  /**
   * The server encountered an unexpected error (such as a CGI script crash)
   * that prevents the request from being fulfilled.
   */
  public static final int HTTP_INTERNAL_ERROR   = 500;

  /**
   * The server does not support the requested functionality.  
   * @since 1.3
   */
  static final int HTTP_NOT_IMPLEMENTED = 501;

  /**
   * The proxy encountered a bad response from the server it was proxy-ing for
   */
  public static final int HTTP_BAD_GATEWAY = 502;

  /**
   * The HTTP service is not availalble, such as because it is overloaded
   * and does not want additional requests.
   */
  public static final int HTTP_UNAVAILABLE = 503;

  /**
   * The proxy timed out getting a reply from the remote server it was
   * proxy-ing for.
   */
  public static final int HTTP_GATEWAY_TIMEOUT = 504;

  /**
   * This server does not support the protocol version requested.
   */
  public static final int HTTP_VERSION = 505;

  // Non-HTTP response static variables

  /**
   * Flag to indicate whether or not redirects should be automatically
   * followed by default.
   */
  private static boolean followRedirects = true;

  /**
   * 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
292

293 294 295
  /**
   * The requested method in use for this connection. Default is GET.
   */
Tom Tromey committed
296
  protected String method = "GET";
297 298 299 300

  /**
   * The response code received from the server
   */
Tom Tromey committed
301
  protected int responseCode = -1;
302 303 304 305 306 307 308 309 310

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

  /**
   * If this instance should follow redirect requests.
   */
311
  protected boolean instanceFollowRedirects = followRedirects;
Tom Tromey committed
312

313 314 315 316 317
  /**
   * Whether we alreadt got a valid response code for this connection.
   * Used by <code>getResponceCode()</code> and
   * <code>getResponseMessage()</code>.
   */
318
  private boolean gotResponseVals = false;
Tom Tromey committed
319

320 321 322 323 324
  /**
   * Create an HttpURLConnection for the specified URL
   *
   * @param url The URL to create this connection for.
   */
Tom Tromey committed
325 326 327 328
  protected HttpURLConnection(URL url)
  {
    super(url);
  }
329 330 331 332
  
  /**   
   * Closes the connection to the server.
   */
Tom Tromey committed
333 334
  public abstract void disconnect();

335 336 337 338 339 340
  /** 
   * Returns a boolean indicating whether or not this connection is going
   * through a proxy
   * 
   * @return true if through a proxy, false otherwise
   */
Tom Tromey committed
341 342
  public abstract boolean usingProxy();

343 344 345 346
  /**
   * Sets whether HTTP redirects (requests with response code 3xx) should be
   * automatically followed by this class. True by default
   *
347 348
   * @param set true if redirects should be followed, false otherwis.
   *
349 350 351
   * @exception SecurityException If a security manager exists and its
   * checkSetFactory method doesn't allow the operation
   */
Tom Tromey committed
352 353 354 355 356 357 358 359 360 361 362
  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;
  }

363 364 365 366 367 368
  /**
   * Returns a boolean indicating whether or not HTTP redirects will 
   * automatically be followed or not.
   *
   * @return true if redirects will be followed, false otherwise
   */
Tom Tromey committed
369 370 371 372 373
  public static boolean getFollowRedirects()
  {
    return followRedirects;
  }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
  /**
   * 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
   */
Tom Tromey committed
398 399 400 401 402
  public void setRequestMethod(String method) throws ProtocolException
  {
    if (connected)
      throw new ProtocolException("Already connected");

403 404
    method = method.toUpperCase();
    if (valid_methods.indexOf("|" + method + "|") != -1)
Tom Tromey committed
405 406
      this.method = method;
    else
407 408
      throw new ProtocolException("Invalid HTTP request method: " + method);

Tom Tromey committed
409 410
  }

411 412 413 414 415
  /**
   * The request method currently in use for this connection.
   *
   * @return The request method
   */
Tom Tromey committed
416 417 418 419 420
  public String getRequestMethod()
  {
    return method;
  }

421
  /**
422 423 424 425 426 427
   * 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
428 429 430
   *
   * @exception IOException If an error occurs
   */
Tom Tromey committed
431 432
  public int getResponseCode() throws IOException
  {
433 434
    if (!gotResponseVals)
      getResponseVals();
Tom Tromey committed
435 436 437
    return responseCode;
  }

438 439
  /**
   * Gets the HTTP response message, if any, returned along with the
440 441 442 443
   * response code from a server. Null if no response message was set
   * or an error occured while connecting.
   *
   * @return The response message
444 445 446
   *
   * @exception IOException If an error occurs
   */
Tom Tromey committed
447 448
  public String getResponseMessage() throws IOException
  {
449 450
    if (!gotResponseVals)
      getResponseVals();
Tom Tromey committed
451 452 453 454 455
    return responseMessage;
  }

  private void getResponseVals() throws IOException
  {
456 457 458 459 460 461
    // getHeaderField() will connect for us, but do it here first in
    // order to pick up IOExceptions.
    if (!connected)
      connect();
      
    gotResponseVals = true;
Tom Tromey committed
462 463
    // Response is the first header received from the connection.
    String respField = getHeaderField(0);
464 465
    
    if (respField == null || ! respField.startsWith("HTTP/"))
Tom Tromey committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      {
	// 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;
      }
  }

490 491 492 493 494 495 496 497
  /**
   * 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
  {
498 499 500 501 502 503 504 505 506
    URL url = getURL();
    String host = url.getHost();
    int port = url.getPort();
    if (port == -1)
      port = 80;
    
    host = host + ":" + port;
    
    return new SocketPermission(host, "connect");
507 508 509
  }

  /**
510 511 512 513 514 515 516
   * 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.
517 518 519
   */
  public InputStream getErrorStream ()
  {
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    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);
      }
554
  }
Tom Tromey committed
555

556 557 558 559 560 561 562 563 564 565
  /**
   * 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);
  }
Tom Tromey committed
566
}