2003-12-26 Guilhem Lavaux <guilhem@kaffe.org>
[official-gcc.git] / libjava / java / net / HttpURLConnection.java
blob2f12fe57d469e27b860fdfcc361e2f6d07b21ce3
1 /* HttpURLConnection.java - Subclass of communications links using
2 Hypertext Transfer Protocol.
3 Copyright (C) 1998, 1999, 2000, 2002, 2003 Free Software Foundation
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA.
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
40 package java.net;
42 import java.io.InputStream;
43 import java.io.IOException;
44 import java.io.PushbackInputStream;
45 import java.security.Permission;
48 * Written using on-line Java Platform 1.2 API Specification, as well
49 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
50 * Status: Believed complete and correct.
53 /**
54 * This class provides a common abstract implementation for those
55 * URL connection classes that will connect using the HTTP protocol.
56 * In addition to the functionality provided by the URLConnection
57 * class, it defines constants for HTTP return code values and
58 * methods for setting the HTTP request method and determining whether
59 * or not to follow redirects.
61 * @since 1.1
63 * @author Warren Levy (warrenl@cygnus.com)
64 * @author Aaron M. Renn (arenn@urbanophile.com)
66 public abstract class HttpURLConnection extends URLConnection
68 /* HTTP Success Response Codes */
70 /**
71 * Indicates that the client may continue with its request. This value
72 * is specified as part of RFC 2068 but was not included in Sun's JDK, so
73 * beware of using this value
75 static final int HTTP_CONTINUE = 100;
77 /**
78 * Indicates the request succeeded.
80 public static final int HTTP_OK = 200;
82 /**
83 * The requested resource has been created.
85 public static final int HTTP_CREATED = 201;
87 /**
88 * The request has been accepted for processing but has not completed.
89 * There is no guarantee that the requested action will actually ever
90 * be completed succesfully, but everything is ok so far.
92 public static final int HTTP_ACCEPTED = 202;
94 /**
95 * The meta-information returned in the header is not the actual data
96 * from the original server, but may be from a local or other copy.
97 * Normally this still indicates a successful completion.
99 public static final int HTTP_NOT_AUTHORITATIVE = 203;
102 * The server performed the request, but there is no data to send
103 * back. This indicates that the user's display should not be changed.
105 public static final int HTTP_NO_CONTENT = 204;
108 * The server performed the request, but there is no data to sent back,
109 * however, the user's display should be "reset" to clear out any form
110 * fields entered.
112 public static final int HTTP_RESET = 205;
115 * The server completed the partial GET request for the resource.
117 public static final int HTTP_PARTIAL = 206;
120 /* HTTP Redirection Response Codes */
123 * There is a list of choices available for the requested resource.
125 public static final int HTTP_MULT_CHOICE = 300;
128 * The resource has been permanently moved to a new location.
130 public static final int HTTP_MOVED_PERM = 301;
133 * The resource requested has been temporarily moved to a new location.
135 public static final int HTTP_MOVED_TEMP = 302;
138 * The response to the request issued is available at another location.
140 public static final int HTTP_SEE_OTHER = 303;
143 * The document has not been modified since the criteria specified in
144 * a conditional GET.
146 public static final int HTTP_NOT_MODIFIED = 304;
149 * The requested resource needs to be accessed through a proxy.
151 public static final int HTTP_USE_PROXY = 305;
154 /* HTTP Client Error Response Codes */
157 * The request was misformed or could not be understood.
159 public static final int HTTP_BAD_REQUEST = 400;
162 * The request made requires user authorization. Try again with
163 * a correct authentication header.
165 public static final int HTTP_UNAUTHORIZED = 401;
168 * Code reserved for future use - I hope way in the future.
170 public static final int HTTP_PAYMENT_REQUIRED = 402;
173 * There is no permission to access the requested resource.
175 public static final int HTTP_FORBIDDEN = 403;
178 * The requested resource was not found.
180 public static final int HTTP_NOT_FOUND = 404;
183 * The specified request method is not allowed for this resource.
185 public static final int HTTP_BAD_METHOD = 405;
188 * Based on the input headers sent, the resource returned in response
189 * to the request would not be acceptable to the client.
191 public static final int HTTP_NOT_ACCEPTABLE = 406;
194 * The client must authenticate with a proxy prior to attempting this
195 * request.
197 public static final int HTTP_PROXY_AUTH = 407;
200 * The request timed out.
202 public static final int HTTP_CLIENT_TIMEOUT = 408;
205 * There is a conflict between the current state of the resource and the
206 * requested action.
208 public static final int HTTP_CONFLICT = 409;
211 * The requested resource is no longer available. This ususally indicates
212 * a permanent condition.
214 public static final int HTTP_GONE = 410;
217 * A Content-Length header is required for this request, but was not
218 * supplied.
220 public static final int HTTP_LENGTH_REQUIRED = 411;
223 * A client specified pre-condition was not met on the server.
225 public static final int HTTP_PRECON_FAILED = 412;
228 * The request sent was too large for the server to handle.
230 public static final int HTTP_ENTITY_TOO_LARGE = 413;
233 * The name of the resource specified was too long.
235 public static final int HTTP_REQ_TOO_LONG = 414;
238 * The request is in a format not supported by the requested resource.
240 public static final int HTTP_UNSUPPORTED_TYPE = 415;
243 /* HTTP Server Error Response Codes */
246 * This error code indicates that some sort of server error occurred.
248 * @deprecated
250 public static final int HTTP_SERVER_ERROR = 500;
253 * The server encountered an unexpected error (such as a CGI script crash)
254 * that prevents the request from being fulfilled.
256 public static final int HTTP_INTERNAL_ERROR = 500;
259 * The server does not support the requested functionality.
260 * @since 1.3
262 public static final int HTTP_NOT_IMPLEMENTED = 501;
265 * The proxy encountered a bad response from the server it was proxy-ing for
267 public static final int HTTP_BAD_GATEWAY = 502;
270 * The HTTP service is not availalble, such as because it is overloaded
271 * and does not want additional requests.
273 public static final int HTTP_UNAVAILABLE = 503;
276 * The proxy timed out getting a reply from the remote server it was
277 * proxy-ing for.
279 public static final int HTTP_GATEWAY_TIMEOUT = 504;
282 * This server does not support the protocol version requested.
284 public static final int HTTP_VERSION = 505;
286 // Non-HTTP response static variables
289 * Flag to indicate whether or not redirects should be automatically
290 * followed by default.
292 private static boolean followRedirects = true;
295 * This is a list of valid request methods, separated by "|" characters.
297 private static String valid_methods
298 = "|GET|POST|HEAD|OPTIONS|PUT|DELETE|TRACE|";
300 // Instance Variables
303 * The requested method in use for this connection. Default is GET.
305 protected String method = "GET";
308 * The response code received from the server
310 protected int responseCode = -1;
313 * The response message string received from the server.
315 protected String responseMessage = null;
318 * If this instance should follow redirect requests.
320 protected boolean instanceFollowRedirects = followRedirects;
323 * Whether we alreadt got a valid response code for this connection.
324 * Used by <code>getResponceCode()</code> and
325 * <code>getResponseMessage()</code>.
327 private boolean gotResponseVals = false;
330 * Create an HttpURLConnection for the specified URL
332 * @param url The URL to create this connection for.
334 protected HttpURLConnection(URL url)
336 super(url);
339 /**
340 * Closes the connection to the server.
342 public abstract void disconnect();
344 /**
345 * Returns a boolean indicating whether or not this connection is going
346 * through a proxy
348 * @return true if through a proxy, false otherwise
350 public abstract boolean usingProxy();
353 * Sets whether HTTP redirects (requests with response code 3xx) should be
354 * automatically followed by this class. True by default
356 * @param set true if redirects should be followed, false otherwis.
358 * @exception SecurityException If a security manager exists and its
359 * checkSetFactory method doesn't allow the operation
361 public static void setFollowRedirects(boolean set)
363 // Throw an exception if an extant security mgr precludes
364 // setting the factory.
365 SecurityManager s = System.getSecurityManager();
366 if (s != null)
367 s.checkSetFactory();
369 followRedirects = set;
373 * Returns a boolean indicating whether or not HTTP redirects will
374 * automatically be followed or not.
376 * @return true if redirects will be followed, false otherwise
378 public static boolean getFollowRedirects()
380 return followRedirects;
384 * Returns the value of this HttpURLConnection's instanceFollowRedirects
385 * field
387 public boolean getInstanceFollowRedirects ()
389 return instanceFollowRedirects;
393 * Sets the value of this HttpURLConnection's instanceFollowRedirects field
395 public void setInstanceFollowRedirects (boolean follow)
397 instanceFollowRedirects = follow;
401 * Set the method for the URL request, one of:
402 * GET POST HEAD OPTIONS PUT DELETE TRACE are legal
404 * @exception ProtocolException If the method cannot be reset or if the
405 * requested method isn't valid for HTTP
407 public void setRequestMethod(String method) throws ProtocolException
409 if (connected)
410 throw new ProtocolException("Already connected");
412 method = method.toUpperCase();
413 if (valid_methods.indexOf("|" + method + "|") != -1)
414 this.method = method;
415 else
416 throw new ProtocolException("Invalid HTTP request method: " + method);
421 * The request method currently in use for this connection.
423 * @return The request method
425 public String getRequestMethod()
427 return method;
431 * Gets the status code from an HTTP response message, or -1 if
432 * the response code could not be determined.
433 * Note that all valid response codes have class variables
434 * defined for them in this class.
436 * @return The response code
438 * @exception IOException If an error occurs
440 public int getResponseCode() throws IOException
442 if (!gotResponseVals)
443 getResponseVals();
444 return responseCode;
448 * Gets the HTTP response message, if any, returned along with the
449 * response code from a server. Null if no response message was set
450 * or an error occured while connecting.
452 * @return The response message
454 * @exception IOException If an error occurs
456 public String getResponseMessage() throws IOException
458 if (!gotResponseVals)
459 getResponseVals();
460 return responseMessage;
463 private void getResponseVals() throws IOException
465 // getHeaderField() will connect for us, but do it here first in
466 // order to pick up IOExceptions.
467 if (!connected)
468 connect();
470 gotResponseVals = true;
472 // If responseCode not yet explicitly set by subclass
473 if (responseCode == -1)
475 // Response is the first header received from the connection.
476 String respField = getHeaderField(0);
478 if (respField == null || ! respField.startsWith("HTTP/"))
480 // Set to default values on failure.
481 responseCode = -1;
482 responseMessage = null;
483 return;
486 int firstSpc, nextSpc;
487 firstSpc = respField.indexOf(' ');
488 nextSpc = respField.indexOf(' ', firstSpc + 1);
489 responseMessage = respField.substring(nextSpc + 1);
490 String codeStr = respField.substring(firstSpc + 1, nextSpc);
493 responseCode = Integer.parseInt(codeStr);
495 catch (NumberFormatException e)
497 // Set to default values on failure.
498 responseCode = -1;
499 responseMessage = null;
505 * Returns a permission object representing the permission necessary to make
506 * the connection represented by this object
508 * @exception IOException If an error occurs
510 public Permission getPermission() throws IOException
512 URL url = getURL();
513 String host = url.getHost();
514 int port = url.getPort();
515 if (port == -1)
516 port = 80;
518 host = host + ":" + port;
520 return new SocketPermission(host, "connect");
524 * This method allows the caller to retrieve any data that might have
525 * been sent despite the fact that an error occurred. For example, the
526 * HTML page sent along with a 404 File Not Found error. If the socket
527 * is not connected, or if no error occurred or no data was returned,
528 * this method returns <code>null</code>.
530 * @return An <code>InputStream</code> for reading error data.
532 public InputStream getErrorStream ()
534 if (!connected)
535 return(null);
537 int code;
538 try
540 code = getResponseCode();
542 catch(IOException e)
544 code = -1;
547 if (code == -1)
548 return(null);
550 if (((code/100) != 4) || ((code/100) != 5))
551 return(null);
555 PushbackInputStream pbis = new PushbackInputStream(getInputStream());
557 int i = pbis.read();
558 if (i == -1)
559 return(null);
561 pbis.unread(i);
562 return(pbis);
564 catch(IOException e)
566 return(null);
571 * Returns the value of the named field parsed as date
573 public long getHeaderFieldDate (String key, long value)
575 // FIXME: implement this correctly
576 // http://www.w3.org/Protocols/HTTP-NG/ng-notes.txt
578 return super.getHeaderFieldDate (key, value);