Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - HttpURLConnection Class



Java HttpURLConnection Class

java.net.HttpURLConnection, 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 URL.openConnection() 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 URL.openConnection() 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

Sr.No. Field & Description
1

protected int chunkLength

The chunk-length when using chunked encoding streaming mode for output.

2

protected int fixedContentLength

The fixed content-length when using fixed-length streaming mode.

3

protected long fixedContentLengthLong

The fixed content-length when using fixed-length streaming mode.

4

static int HTTP_ACCEPTED

HTTP Status-Code 202: Accepted.

5

static int HTTP_BAD_GATEWAY

HTTP Status-Code 502: Bad Gateway.

6

static int HTTP_BAD_METHOD

HTTP Status-Code 405: Method Not Allowed.

7

static int HTTP_BAD_REQUEST

HTTP Status-Code 400: Bad Request.

8

static int HTTP_CLIENT_TIMEOUT

HTTP Status-Code 408: Request Time-Out.

9

static int HTTP_CONFLICT

HTTP Status-Code 409: Conflict.

10

static int HTTP_CREATED

HTTP Status-Code 201: Created.

11

static int HTTP_ENTITY_TOO_LARGE

HTTP Status-Code 413: Request Entity Too Large.

12

static int HTTP_FORBIDDEN

HTTP Status-Code 403: Forbidden.

13

static int HTTP_GATEWAY_TIMEOUT

HTTP Status-Code 504: Gateway Timeout.

14

static int HTTP_GONE

HTTP Status-Code 410: Gone.

15

static int HTTP_INTERNAL_ERROR

HTTP Status-Code 500: Internal Server Error.

16

static int HTTP_LENGTH_REQUIRED

HTTP Status-Code 411: Length Required.

17

static int HTTP_MOVED_PERM

HTTP Status-Code 301: Moved Permanently.

18

static int HTTP_MOVED_TEMP

HTTP Status-Code 302: Temporary Redirect.

19

static int HTTP_MULT_CHOICE

HTTP Status-Code 300: Multiple Choices.

20

static int HTTP_NO_CONTENT

HTTP Status-Code 204: No Content.

21

static int HTTP_NOT_ACCEPTABLE

HTTP Status-Code 406: Not Acceptable.

22

static int HTTP_NOT_AUTHORITATIVE

HTTP Status-Code 203: Non-Authoritative Information.

23

static int HTTP_NOT_FOUND

HTTP Status-Code 404: Not Found.

24

static int HTTP_NOT_IMPLEMENTED

HTTP Status-Code 501: Not Implemented.

25

static int HTTP_NOT_MODIFIED

HTTP Status-Code 304: Not Modified.

26

static int HTTP_OK

HTTP Status-Code 200: OK.

27

static int HTTP_PARTIAL

HTTP Status-Code 206: Partial Content.

28

static int HTTP_PAYMENT_REQUIRED

HTTP Status-Code 402: Payment Required.

29

static int HTTP_PRECON_FAILED

HTTP Status-Code 412: Precondition Failed.

30

static int HTTP_PROXY_AUTH

HTTP Status-Code 407: Proxy Authentication Required.

31

static int HTTP_REQ_TOO_LONG

HTTP Status-Code 414: Request-URI Too Large.

32

static int HTTP_RESET

HTTP Status-Code 205: Reset Content.

33

static int HTTP_SEE_OTHER

HTTP Status-Code 303: See Other.

34

static int HTTP_UNAUTHORIZED

HTTP Status-Code 401: Unauthorized.

35

static int HTTP_UNAVAILABLE

HTTP Status-Code 503: Service Unavailable.

36

static int HTTP_UNSUPPORTED_TYPE

HTTP Status-Code 415: Unsupported Media Type.

37

static int HTTP_USE_PROXY

HTTP Status-Code 305: Use Proxy.

38

static int HTTP_VERSION

HTTP Status-Code 505: HTTP Version Not Supported.

39

protected boolean instanceFollowRedirects

If true, the protocol will automatically follow redirects.

40

protected String method

The HTTP method (GET,POST,PUT,etc.).

41

protected int responseCode

An int representing the three digit HTTP Status-Code.

42

protected String responseMessage

The HTTP response message.

HttpURLConnection Class Methods

The HttpURLConnection class has many methods for setting or determining information about the connection, including the following −

Sr.No. Method & Description
1

abstract void disconnect()

Indicates that other requests to the server are unlikely in the near future.

2

InputStream getErrorStream()

Returns the error stream if the connection failed but the server sent useful data nonetheless.

3

static boolean getFollowRedirects()

Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

4

String getHeaderField(int n)

Returns the value for the nth header field.

5

String getHeaderFieldKey(int n)

Returns the key for the nth header field.

6

boolean getInstanceFollowRedirects()

Returns the value of this HttpURLConnection's instanceFollowRedirects field.

7

Permission getPermission()

Returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

8

String getRequestMethod()

Get the request method.

9

int getResponseCode()

Gets the status code from an HTTP response message.

10

String getResponseMessage()

Gets the HTTP response message, if any, returned along with the response code from a server.

11

void setAuthenticator(Authenticator auth)

Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.

12

void setChunkedStreamingMode(int chunklen)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

13

void setFixedLengthStreamingMode(int contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

14

void setFixedLengthStreamingMode(long contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

15

static void setFollowRedirects(boolean set)

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.

17

void setRequestMethod(String method)

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.

18

abstract boolean usingProxy()

Indicates if the connection is going through a proxy.

Extends

This class extends following classes

  • java.lang.Object

  • java.net.URLConnection

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 com.tutorialspoint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpUrlConnectionDemo {
   public static void main(String [] args) {
      try {
         URL url = new URL("https://www.tutorialspoint.com");
         URLConnection urlConnection = url.openConnection();
         HttpURLConnection connection = null;
         if(urlConnection instanceof HttpURLConnection) {
            connection = (HttpURLConnection) urlConnection;
         }else {
            System.out.println("Please enter an HTTP URL.");
            return;
         }
         
         BufferedReader in = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
         String urlString = "";
         String current;
         
         while((current = in.readLine()) != null) {
            urlString += current;
         }
         System.out.println(urlString);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

A sample run of this program will produce the following result −

Output

$ java HttpURLConnection

.....a complete HTML content of home page of tutorialspoint.com.....
Advertisements