blob: eb21c7f3ba468f64560a0d0f9d40d5a5c1041a49 [file] [log] [blame]
J. Duke319a3b92007-12-01 00:00:00 +00001/*
2 * Copyright 1996-2007 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26package java.net;
27
28import java.io.InputStream;
29import java.io.IOException;
30import java.security.Permission;
31import java.util.Date;
32
33/**
34 * A URLConnection with support for HTTP-specific features. See
35 * <A HREF="http://www.w3.org/pub/WWW/Protocols/"> the spec </A> for
36 * details.
37 * <p>
38 *
39 * Each HttpURLConnection instance is used to make a single request
40 * but the underlying network connection to the HTTP server may be
41 * transparently shared by other instances. Calling the close() methods
42 * on the InputStream or OutputStream of an HttpURLConnection
43 * after a request may free network resources associated with this
44 * instance but has no effect on any shared persistent connection.
45 * Calling the disconnect() method may close the underlying socket
46 * if a persistent connection is otherwise idle at that time.
47 *
48 * <P>The HTTP protocol handler has a few settings that can be accessed through
49 * System Properties. This covers
50 * <a href="doc-files/net-properties.html#Proxies">Proxy settings</a> as well as
51 * <a href="doc-files/net-properties.html#MiscHTTP"> various other settings</a>.
52 * </P>
53 *
54 * @see java.net.HttpURLConnection#disconnect()
55 * @since JDK1.1
56 */
57abstract public class HttpURLConnection extends URLConnection {
58 /* instance variables */
59
60 /**
61 * The HTTP method (GET,POST,PUT,etc.).
62 */
63 protected String method = "GET";
64
65 /**
66 * The chunk-length when using chunked encoding streaming mode for output.
67 * A value of <code>-1</code> means chunked encoding is disabled for output.
68 * @since 1.5
69 */
70 protected int chunkLength = -1;
71
72 /**
73 * The fixed content-length when using fixed-length streaming mode.
74 * A value of <code>-1</code> means fixed-length streaming mode is disabled
75 * for output.
76 * @since 1.5
77 */
78 protected int fixedContentLength = -1;
79
80 /**
81 * Returns the key for the <code>n</code><sup>th</sup> header field.
82 * Some implementations may treat the <code>0</code><sup>th</sup>
83 * header field as special, i.e. as the status line returned by the HTTP
84 * server. In this case, {@link #getHeaderField(int) getHeaderField(0)} returns the status
85 * line, but <code>getHeaderFieldKey(0)</code> returns null.
86 *
87 * @param n an index, where n >=0.
88 * @return the key for the <code>n</code><sup>th</sup> header field,
89 * or <code>null</code> if the key does not exist.
90 */
91 public String getHeaderFieldKey (int n) {
92 return null;
93 }
94
95 /**
96 * This method is used to enable streaming of a HTTP request body
97 * without internal buffering, when the content length is known in
98 * advance.
99 * <p>
100 * An exception will be thrown if the application
101 * attempts to write more data than the indicated
102 * content-length, or if the application closes the OutputStream
103 * before writing the indicated amount.
104 * <p>
105 * When output streaming is enabled, authentication
106 * and redirection cannot be handled automatically.
107 * A HttpRetryException will be thrown when reading
108 * the response if authentication or redirection are required.
109 * This exception can be queried for the details of the error.
110 * <p>
111 * This method must be called before the URLConnection is connected.
112 *
113 * @param contentLength The number of bytes which will be written
114 * to the OutputStream.
115 *
116 * @throws IllegalStateException if URLConnection is already connected
117 * or if a different streaming mode is already enabled.
118 *
119 * @throws IllegalArgumentException if a content length less than
120 * zero is specified.
121 *
122 * @see #setChunkedStreamingMode(int)
123 * @since 1.5
124 */
125 public void setFixedLengthStreamingMode (int contentLength) {
126 if (connected) {
127 throw new IllegalStateException ("Already connected");
128 }
129 if (chunkLength != -1) {
130 throw new IllegalStateException ("Chunked encoding streaming mode set");
131 }
132 if (contentLength < 0) {
133 throw new IllegalArgumentException ("invalid content length");
134 }
135 fixedContentLength = contentLength;
136 }
137
138 /* Default chunk size (including chunk header) if not specified;
139 * we want to keep this in sync with the one defined in
140 * sun.net.www.http.ChunkedOutputStream
141 */
142 private static final int DEFAULT_CHUNK_SIZE = 4096;
143
144 /**
145 * This method is used to enable streaming of a HTTP request body
146 * without internal buffering, when the content length is <b>not</b>
147 * known in advance. In this mode, chunked transfer encoding
148 * is used to send the request body. Note, not all HTTP servers
149 * support this mode.
150 * <p>
151 * When output streaming is enabled, authentication
152 * and redirection cannot be handled automatically.
153 * A HttpRetryException will be thrown when reading
154 * the response if authentication or redirection are required.
155 * This exception can be queried for the details of the error.
156 * <p>
157 * This method must be called before the URLConnection is connected.
158 *
159 * @param chunklen The number of bytes to write in each chunk.
160 * If chunklen is less than or equal to zero, a default
161 * value will be used.
162 *
163 * @throws IllegalStateException if URLConnection is already connected
164 * or if a different streaming mode is already enabled.
165 *
166 * @see #setFixedLengthStreamingMode(int)
167 * @since 1.5
168 */
169 public void setChunkedStreamingMode (int chunklen) {
170 if (connected) {
171 throw new IllegalStateException ("Can't set streaming mode: already connected");
172 }
173 if (fixedContentLength != -1) {
174 throw new IllegalStateException ("Fixed length streaming mode set");
175 }
176 chunkLength = chunklen <=0? DEFAULT_CHUNK_SIZE : chunklen;
177 }
178
179 /**
180 * Returns the value for the <code>n</code><sup>th</sup> header field.
181 * Some implementations may treat the <code>0</code><sup>th</sup>
182 * header field as special, i.e. as the status line returned by the HTTP
183 * server.
184 * <p>
185 * This method can be used in conjunction with the
186 * {@link #getHeaderFieldKey getHeaderFieldKey} method to iterate through all
187 * the headers in the message.
188 *
189 * @param n an index, where n>=0.
190 * @return the value of the <code>n</code><sup>th</sup> header field,
191 * or <code>null</code> if the value does not exist.
192 * @see java.net.HttpURLConnection#getHeaderFieldKey(int)
193 */
194 public String getHeaderField(int n) {
195 return null;
196 }
197
198 /**
199 * An <code>int</code> representing the three digit HTTP Status-Code.
200 * <ul>
201 * <li> 1xx: Informational
202 * <li> 2xx: Success
203 * <li> 3xx: Redirection
204 * <li> 4xx: Client Error
205 * <li> 5xx: Server Error
206 * </ul>
207 */
208 protected int responseCode = -1;
209
210 /**
211 * The HTTP response message.
212 */
213 protected String responseMessage = null;
214
215 /* static variables */
216
217 /* do we automatically follow redirects? The default is true. */
218 private static boolean followRedirects = true;
219
220 /**
221 * If <code>true</code>, the protocol will automatically follow redirects.
222 * If <code>false</code>, the protocol will not automatically follow
223 * redirects.
224 * <p>
225 * This field is set by the <code>setInstanceFollowRedirects</code>
226 * method. Its value is returned by the <code>getInstanceFollowRedirects</code>
227 * method.
228 * <p>
229 * Its default value is based on the value of the static followRedirects
230 * at HttpURLConnection construction time.
231 *
232 * @see java.net.HttpURLConnection#setInstanceFollowRedirects(boolean)
233 * @see java.net.HttpURLConnection#getInstanceFollowRedirects()
234 * @see java.net.HttpURLConnection#setFollowRedirects(boolean)
235 */
236 protected boolean instanceFollowRedirects = followRedirects;
237
238 /* valid HTTP methods */
239 private static final String[] methods = {
240 "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
241 };
242
243 /**
244 * Constructor for the HttpURLConnection.
245 * @param u the URL
246 */
247 protected HttpURLConnection (URL u) {
248 super(u);
249 }
250
251 /**
252 * Sets whether HTTP redirects (requests with response code 3xx) should
253 * be automatically followed by this class. True by default. Applets
254 * cannot change this variable.
255 * <p>
256 * If there is a security manager, this method first calls
257 * the security manager's <code>checkSetFactory</code> method
258 * to ensure the operation is allowed.
259 * This could result in a SecurityException.
260 *
261 * @param set a <code>boolean</code> indicating whether or not
262 * to follow HTTP redirects.
263 * @exception SecurityException if a security manager exists and its
264 * <code>checkSetFactory</code> method doesn't
265 * allow the operation.
266 * @see SecurityManager#checkSetFactory
267 * @see #getFollowRedirects()
268 */
269 public static void setFollowRedirects(boolean set) {
270 SecurityManager sec = System.getSecurityManager();
271 if (sec != null) {
272 // seems to be the best check here...
273 sec.checkSetFactory();
274 }
275 followRedirects = set;
276 }
277
278 /**
279 * Returns a <code>boolean</code> indicating
280 * whether or not HTTP redirects (3xx) should
281 * be automatically followed.
282 *
283 * @return <code>true</code> if HTTP redirects should
284 * be automatically followed, <tt>false</tt> if not.
285 * @see #setFollowRedirects(boolean)
286 */
287 public static boolean getFollowRedirects() {
288 return followRedirects;
289 }
290
291 /**
292 * Sets whether HTTP redirects (requests with response code 3xx) should
293 * be automatically followed by this <code>HttpURLConnection</code>
294 * instance.
295 * <p>
296 * The default value comes from followRedirects, which defaults to
297 * true.
298 *
299 * @param followRedirects a <code>boolean</code> indicating
300 * whether or not to follow HTTP redirects.
301 *
302 * @see java.net.HttpURLConnection#instanceFollowRedirects
303 * @see #getInstanceFollowRedirects
304 * @since 1.3
305 */
306 public void setInstanceFollowRedirects(boolean followRedirects) {
307 instanceFollowRedirects = followRedirects;
308 }
309
310 /**
311 * Returns the value of this <code>HttpURLConnection</code>'s
312 * <code>instanceFollowRedirects</code> field.
313 *
314 * @return the value of this <code>HttpURLConnection</code>'s
315 * <code>instanceFollowRedirects</code> field.
316 * @see java.net.HttpURLConnection#instanceFollowRedirects
317 * @see #setInstanceFollowRedirects(boolean)
318 * @since 1.3
319 */
320 public boolean getInstanceFollowRedirects() {
321 return instanceFollowRedirects;
322 }
323
324 /**
325 * Set the method for the URL request, one of:
326 * <UL>
327 * <LI>GET
328 * <LI>POST
329 * <LI>HEAD
330 * <LI>OPTIONS
331 * <LI>PUT
332 * <LI>DELETE
333 * <LI>TRACE
334 * </UL> are legal, subject to protocol restrictions. The default
335 * method is GET.
336 *
337 * @param method the HTTP method
338 * @exception ProtocolException if the method cannot be reset or if
339 * the requested method isn't valid for HTTP.
340 * @see #getRequestMethod()
341 */
342 public void setRequestMethod(String method) throws ProtocolException {
343 if (connected) {
344 throw new ProtocolException("Can't reset method: already connected");
345 }
346 // This restriction will prevent people from using this class to
347 // experiment w/ new HTTP methods using java. But it should
348 // be placed for security - the request String could be
349 // arbitrarily long.
350
351 for (int i = 0; i < methods.length; i++) {
352 if (methods[i].equals(method)) {
353 this.method = method;
354 return;
355 }
356 }
357 throw new ProtocolException("Invalid HTTP method: " + method);
358 }
359
360 /**
361 * Get the request method.
362 * @return the HTTP request method
363 * @see #setRequestMethod(java.lang.String)
364 */
365 public String getRequestMethod() {
366 return method;
367 }
368
369 /**
370 * Gets the status code from an HTTP response message.
371 * For example, in the case of the following status lines:
372 * <PRE>
373 * HTTP/1.0 200 OK
374 * HTTP/1.0 401 Unauthorized
375 * </PRE>
376 * It will return 200 and 401 respectively.
377 * Returns -1 if no code can be discerned
378 * from the response (i.e., the response is not valid HTTP).
379 * @throws IOException if an error occurred connecting to the server.
380 * @return the HTTP Status-Code, or -1
381 */
382 public int getResponseCode() throws IOException {
383 /*
384 * We're got the response code already
385 */
386 if (responseCode != -1) {
387 return responseCode;
388 }
389
390 /*
391 * Ensure that we have connected to the server. Record
392 * exception as we need to re-throw it if there isn't
393 * a status line.
394 */
395 Exception exc = null;
396 try {
397 getInputStream();
398 } catch (Exception e) {
399 exc = e;
400 }
401
402 /*
403 * If we can't a status-line then re-throw any exception
404 * that getInputStream threw.
405 */
406 String statusLine = getHeaderField(0);
407 if (statusLine == null) {
408 if (exc != null) {
409 if (exc instanceof RuntimeException)
410 throw (RuntimeException)exc;
411 else
412 throw (IOException)exc;
413 }
414 return -1;
415 }
416
417 /*
418 * Examine the status-line - should be formatted as per
419 * section 6.1 of RFC 2616 :-
420 *
421 * Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase
422 *
423 * If status line can't be parsed return -1.
424 */
425 if (statusLine.startsWith("HTTP/1.")) {
426 int codePos = statusLine.indexOf(' ');
427 if (codePos > 0) {
428
429 int phrasePos = statusLine.indexOf(' ', codePos+1);
430 if (phrasePos > 0 && phrasePos < statusLine.length()) {
431 responseMessage = statusLine.substring(phrasePos+1);
432 }
433
434 // deviation from RFC 2616 - don't reject status line
435 // if SP Reason-Phrase is not included.
436 if (phrasePos < 0)
437 phrasePos = statusLine.length();
438
439 try {
440 responseCode = Integer.parseInt
441 (statusLine.substring(codePos+1, phrasePos));
442 return responseCode;
443 } catch (NumberFormatException e) { }
444 }
445 }
446 return -1;
447 }
448
449 /**
450 * Gets the HTTP response message, if any, returned along with the
451 * response code from a server. From responses like:
452 * <PRE>
453 * HTTP/1.0 200 OK
454 * HTTP/1.0 404 Not Found
455 * </PRE>
456 * Extracts the Strings "OK" and "Not Found" respectively.
457 * Returns null if none could be discerned from the responses
458 * (the result was not valid HTTP).
459 * @throws IOException if an error occurred connecting to the server.
460 * @return the HTTP response message, or <code>null</code>
461 */
462 public String getResponseMessage() throws IOException {
463 getResponseCode();
464 return responseMessage;
465 }
466
467 public long getHeaderFieldDate(String name, long Default) {
468 String dateString = getHeaderField(name);
469 try {
470 if (dateString.indexOf("GMT") == -1) {
471 dateString = dateString+" GMT";
472 }
473 return Date.parse(dateString);
474 } catch (Exception e) {
475 }
476 return Default;
477 }
478
479
480 /**
481 * Indicates that other requests to the server
482 * are unlikely in the near future. Calling disconnect()
483 * should not imply that this HttpURLConnection
484 * instance can be reused for other requests.
485 */
486 public abstract void disconnect();
487
488 /**
489 * Indicates if the connection is going through a proxy.
490 * @return a boolean indicating if the connection is
491 * using a proxy.
492 */
493 public abstract boolean usingProxy();
494
495 /**
496 * Returns a {@link SocketPermission} object representing the
497 * permission necessary to connect to the destination host and port.
498 *
499 * @exception IOException if an error occurs while computing
500 * the permission.
501 *
502 * @return a <code>SocketPermission</code> object representing the
503 * permission necessary to connect to the destination
504 * host and port.
505 */
506 public Permission getPermission() throws IOException {
507 int port = url.getPort();
508 port = port < 0 ? 80 : port;
509 String host = url.getHost() + ":" + port;
510 Permission permission = new SocketPermission(host, "connect");
511 return permission;
512 }
513
514 /**
515 * Returns the error stream if the connection failed
516 * but the server sent useful data nonetheless. The
517 * typical example is when an HTTP server responds
518 * with a 404, which will cause a FileNotFoundException
519 * to be thrown in connect, but the server sent an HTML
520 * help page with suggestions as to what to do.
521 *
522 * <p>This method will not cause a connection to be initiated. If
523 * the connection was not connected, or if the server did not have
524 * an error while connecting or if the server had an error but
525 * no error data was sent, this method will return null. This is
526 * the default.
527 *
528 * @return an error stream if any, null if there have been no
529 * errors, the connection is not connected or the server sent no
530 * useful data.
531 */
532 public InputStream getErrorStream() {
533 return null;
534 }
535
536 /**
537 * The response codes for HTTP, as of version 1.1.
538 */
539
540 // REMIND: do we want all these??
541 // Others not here that we do want??
542
543 /* 2XX: generally "OK" */
544
545 /**
546 * HTTP Status-Code 200: OK.
547 */
548 public static final int HTTP_OK = 200;
549
550 /**
551 * HTTP Status-Code 201: Created.
552 */
553 public static final int HTTP_CREATED = 201;
554
555 /**
556 * HTTP Status-Code 202: Accepted.
557 */
558 public static final int HTTP_ACCEPTED = 202;
559
560 /**
561 * HTTP Status-Code 203: Non-Authoritative Information.
562 */
563 public static final int HTTP_NOT_AUTHORITATIVE = 203;
564
565 /**
566 * HTTP Status-Code 204: No Content.
567 */
568 public static final int HTTP_NO_CONTENT = 204;
569
570 /**
571 * HTTP Status-Code 205: Reset Content.
572 */
573 public static final int HTTP_RESET = 205;
574
575 /**
576 * HTTP Status-Code 206: Partial Content.
577 */
578 public static final int HTTP_PARTIAL = 206;
579
580 /* 3XX: relocation/redirect */
581
582 /**
583 * HTTP Status-Code 300: Multiple Choices.
584 */
585 public static final int HTTP_MULT_CHOICE = 300;
586
587 /**
588 * HTTP Status-Code 301: Moved Permanently.
589 */
590 public static final int HTTP_MOVED_PERM = 301;
591
592 /**
593 * HTTP Status-Code 302: Temporary Redirect.
594 */
595 public static final int HTTP_MOVED_TEMP = 302;
596
597 /**
598 * HTTP Status-Code 303: See Other.
599 */
600 public static final int HTTP_SEE_OTHER = 303;
601
602 /**
603 * HTTP Status-Code 304: Not Modified.
604 */
605 public static final int HTTP_NOT_MODIFIED = 304;
606
607 /**
608 * HTTP Status-Code 305: Use Proxy.
609 */
610 public static final int HTTP_USE_PROXY = 305;
611
612 /* 4XX: client error */
613
614 /**
615 * HTTP Status-Code 400: Bad Request.
616 */
617 public static final int HTTP_BAD_REQUEST = 400;
618
619 /**
620 * HTTP Status-Code 401: Unauthorized.
621 */
622 public static final int HTTP_UNAUTHORIZED = 401;
623
624 /**
625 * HTTP Status-Code 402: Payment Required.
626 */
627 public static final int HTTP_PAYMENT_REQUIRED = 402;
628
629 /**
630 * HTTP Status-Code 403: Forbidden.
631 */
632 public static final int HTTP_FORBIDDEN = 403;
633
634 /**
635 * HTTP Status-Code 404: Not Found.
636 */
637 public static final int HTTP_NOT_FOUND = 404;
638
639 /**
640 * HTTP Status-Code 405: Method Not Allowed.
641 */
642 public static final int HTTP_BAD_METHOD = 405;
643
644 /**
645 * HTTP Status-Code 406: Not Acceptable.
646 */
647 public static final int HTTP_NOT_ACCEPTABLE = 406;
648
649 /**
650 * HTTP Status-Code 407: Proxy Authentication Required.
651 */
652 public static final int HTTP_PROXY_AUTH = 407;
653
654 /**
655 * HTTP Status-Code 408: Request Time-Out.
656 */
657 public static final int HTTP_CLIENT_TIMEOUT = 408;
658
659 /**
660 * HTTP Status-Code 409: Conflict.
661 */
662 public static final int HTTP_CONFLICT = 409;
663
664 /**
665 * HTTP Status-Code 410: Gone.
666 */
667 public static final int HTTP_GONE = 410;
668
669 /**
670 * HTTP Status-Code 411: Length Required.
671 */
672 public static final int HTTP_LENGTH_REQUIRED = 411;
673
674 /**
675 * HTTP Status-Code 412: Precondition Failed.
676 */
677 public static final int HTTP_PRECON_FAILED = 412;
678
679 /**
680 * HTTP Status-Code 413: Request Entity Too Large.
681 */
682 public static final int HTTP_ENTITY_TOO_LARGE = 413;
683
684 /**
685 * HTTP Status-Code 414: Request-URI Too Large.
686 */
687 public static final int HTTP_REQ_TOO_LONG = 414;
688
689 /**
690 * HTTP Status-Code 415: Unsupported Media Type.
691 */
692 public static final int HTTP_UNSUPPORTED_TYPE = 415;
693
694 /* 5XX: server error */
695
696 /**
697 * HTTP Status-Code 500: Internal Server Error.
698 * @deprecated it is misplaced and shouldn't have existed.
699 */
700 @Deprecated
701 public static final int HTTP_SERVER_ERROR = 500;
702
703 /**
704 * HTTP Status-Code 500: Internal Server Error.
705 */
706 public static final int HTTP_INTERNAL_ERROR = 500;
707
708 /**
709 * HTTP Status-Code 501: Not Implemented.
710 */
711 public static final int HTTP_NOT_IMPLEMENTED = 501;
712
713 /**
714 * HTTP Status-Code 502: Bad Gateway.
715 */
716 public static final int HTTP_BAD_GATEWAY = 502;
717
718 /**
719 * HTTP Status-Code 503: Service Unavailable.
720 */
721 public static final int HTTP_UNAVAILABLE = 503;
722
723 /**
724 * HTTP Status-Code 504: Gateway Timeout.
725 */
726 public static final int HTTP_GATEWAY_TIMEOUT = 504;
727
728 /**
729 * HTTP Status-Code 505: HTTP Version Not Supported.
730 */
731 public static final int HTTP_VERSION = 505;
732
733}