Home Java Java - HttpURLConnection Class
Java - HttpURLConnection Class
Java HttpURLConnection Class
[Link], is an abstract class which represents the HTTP-specific
URL connection. Instances of this class can be used both to read from and to write to the
resource referenced by the URL.
For example −
If you connect to a URL whose protocol is HTTP, the [Link]() method
returns an HttpURLConnection object.
Steps to make a connection to a URL
Following are the steps to make a connectiion to the URL and start processing.
Invoke [Link]() method to get HttpURLConnection object of an
HTTP based URL.
Update setup parameters and general request properties as required using
connection object various setter methods.
Create a connection to remote object using connect() method of connection object.
Once remote object is available, access the content/headers of the remote object.
HttpURLConnection Class Declaration
public abstract class HttpURLConnection
extends URLConnection
HttpURLConnection Class Fields
[Link]. Field & Description
protected int chunkLength
1
The chunk-length when using chunked encoding streaming mode for output.
protected int fixedContentLength
2
The fixed content-length when using fixed-length streaming mode.
protected long fixedContentLengthLong
3
The fixed content-length when using fixed-length streaming mode.
static int HTTP_ACCEPTED
4
HTTP Status-Code 202: Accepted.
static int HTTP_BAD_GATEWAY
5
HTTP Status-Code 502: Bad Gateway.
static int HTTP_BAD_METHOD
6
HTTP Status-Code 405: Method Not Allowed.
static int HTTP_BAD_REQUEST
7
HTTP Status-Code 400: Bad Request.
static int HTTP_CLIENT_TIMEOUT
8
HTTP Status-Code 408: Request Time-Out.
static int HTTP_CONFLICT
9
HTTP Status-Code 409: Conflict.
static int HTTP_CREATED
10
HTTP Status-Code 201: Created.
static int HTTP_ENTITY_TOO_LARGE
11
HTTP Status-Code 413: Request Entity Too Large.
static int HTTP_FORBIDDEN
12
HTTP Status-Code 403: Forbidden.
static int HTTP_GATEWAY_TIMEOUT
13
HTTP Status-Code 504: Gateway Timeout.
static int HTTP_GONE
14
HTTP Status-Code 410: Gone.
static int HTTP_INTERNAL_ERROR
15
HTTP Status-Code 500: Internal Server Error.
static int HTTP_LENGTH_REQUIRED
16
HTTP Status-Code 411: Length Required.
static int HTTP_MOVED_PERM
17
HTTP Status-Code 301: Moved Permanently.
static int HTTP_MOVED_TEMP
18
HTTP Status-Code 302: Temporary Redirect.
static int HTTP_MULT_CHOICE
19
HTTP Status-Code 300: Multiple Choices.
static int HTTP_NO_CONTENT
20
HTTP Status-Code 204: No Content.
static int HTTP_NOT_ACCEPTABLE
21
HTTP Status-Code 406: Not Acceptable.
static int HTTP_NOT_AUTHORITATIVE
22
HTTP Status-Code 203: Non-Authoritative Information.
static int HTTP_NOT_FOUND
23
HTTP Status-Code 404: Not Found.
static int HTTP_NOT_IMPLEMENTED
24
HTTP Status-Code 501: Not Implemented.
static int HTTP_NOT_MODIFIED
25
HTTP Status-Code 304: Not Modified.
26 static int HTTP_OK
HTTP Status-Code 200: OK.
static int HTTP_PARTIAL
27
HTTP Status-Code 206: Partial Content.
static int HTTP_PAYMENT_REQUIRED
28
HTTP Status-Code 402: Payment Required.
static int HTTP_PRECON_FAILED
29
HTTP Status-Code 412: Precondition Failed.
static int HTTP_PROXY_AUTH
30
HTTP Status-Code 407: Proxy Authentication Required.
static int HTTP_REQ_TOO_LONG
31
HTTP Status-Code 414: Request-URI Too Large.
static int HTTP_RESET
32
HTTP Status-Code 205: Reset Content.
static int HTTP_SEE_OTHER
33
HTTP Status-Code 303: See Other.
static int HTTP_UNAUTHORIZED
34
HTTP Status-Code 401: Unauthorized.
static int HTTP_UNAVAILABLE
35
HTTP Status-Code 503: Service Unavailable.
static int HTTP_UNSUPPORTED_TYPE
36
HTTP Status-Code 415: Unsupported Media Type.
static int HTTP_USE_PROXY
37
HTTP Status-Code 305: Use Proxy.
static int HTTP_VERSION
38
HTTP Status-Code 505: HTTP Version Not Supported.
protected boolean instanceFollowRedirects
39
If true, the protocol will automatically follow redirects.
protected String method
40
The HTTP method (GET,POST,PUT,etc.).
protected int responseCode
41
An int representing the three digit HTTP Status-Code.
protected String responseMessage
42
The HTTP response message.
HttpURLConnection Class Methods
The HttpURLConnection class has many methods for setting or determining information
about the connection, including the following −
[Link]. Method & Description
abstract void disconnect()
1
Indicates that other requests to the server are unlikely in the near future.
InputStream getErrorStream()
2 Returns the error stream if the connection failed but the server sent useful data
nonetheless.
static boolean getFollowRedirects()
3 Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically
followed.
String getHeaderField(int n)
4
Returns the value for the nth header field.
String getHeaderFieldKey(int n)
5
Returns the key for the nth header field.
boolean getInstanceFollowRedirects()
6
Returns the value of this HttpURLConnection's instanceFollowRedirects field.
Permission getPermission()
7 Returns a SocketPermission object representing the permission necessary to connect to the
destination host and port.
String getRequestMethod()
8
Get the request method.
int getResponseCode()
9
Gets the status code from an HTTP response message.
String getResponseMessage()
10 Gets the HTTP response message, if any, returned along with the response code from a
server.
void setAuthenticator(Authenticator auth)
11 Supplies an Authenticator to be used when authentication is requested through the HTTP
protocol for this HttpURLConnection.
void setChunkedStreamingMode(int chunklen)
12 This method is used to enable streaming of a HTTP request body without internal buffering,
when the content length is not known in advance.
void setFixedLengthStreamingMode(int contentLength)
13 This method is used to enable streaming of a HTTP request body without internal buffering,
when the content length is known in advance.
void setFixedLengthStreamingMode(long contentLength)
14 This method is used to enable streaming of a HTTP request body without internal buffering,
when the content length is known in advance.
static void setFollowRedirects(boolean set)
15 Sets whether HTTP redirects (requests with response code 3xx) should be automatically
followed by this class.
16 void setInstanceFollowRedirects(boolean followRedirects)
Sets whether HTTP redirects (requests with response code 3xx) should be automatically
followed by this HttpURLConnection instance.
void setRequestMethod(String method)
17 Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE
are legal, subject to protocol restrictions.
abstract boolean usingProxy()
18
Indicates if the connection is going through a proxy.
Extends
This class extends following classes
[Link]
[Link]
Example of Java HttpURLConnection Class
The following HttpURLConnection program connects to a URL entered from the command
line.
If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and
the data in the resource is read one line at a time.
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HttpUrlConnectionDemo {
public static void main(String [] args) {
try {
URL url = new URL("[Link]
URLConnection urlConnection = [Link]();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
}else {
[Link]("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));
String urlString = "";
String current;
while((current = [Link]()) != null) {
urlString += current;
}
[Link](urlString);
} catch (IOException e) {
[Link]();
}
}
}
A sample run of this program will produce the following result −
Output
$ java HttpURLConnection
.....a complete HTML content of home page of [Link].....