Java HttpURLConnection Class - Manage HTTP Requests Efficiently

Learn how to use Java's HttpURLConnection class to handle HTTP connections, retrieve response codes, headers, and manage data from HTTP URLs. As a subclass of URLConnection, HttpURLConnection offers powerful tools for building robust Java applications that interact seamlessly with web resources.



Java HttpURLConnection Class

The Java HttpURLConnection class is specifically for HTTP URLs. It helps retrieve information like header info, status codes, and response codes from HTTP URLs. It is a subclass of the URLConnection class.

HttpURLConnection Constructor

Constructor Description
protected HttpURLConnection(URL u) Constructs an instance of HttpURLConnection class.

Java HttpURLConnection Methods

Method Description
void disconnect() Indicates that further requests from the server are unlikely.
InputStream getErrorStream() Returns the error stream if the connection failed but the server sent useful data.
static boolean getFollowRedirects() Checks if HTTP redirects should be automatically followed.
String getHeaderField(int n) Returns the value of the nth header field.
long getHeaderFieldDate(String name, long Default) Returns the value of the named field parsed as a date.
String getHeaderFieldKey(int n) Returns the key for the nth header field.
boolean getInstanceFollowRedirects() Returns the value of HttpURLConnection's instance FollowRedirects field.
Permission getPermission() Returns the SocketPermission object representing the permission to connect to the destination host and port.
String getRequestMethod() Gets the request method.
int getResponseCode() Gets the response code from an HTTP response message.
String getResponseMessage() Gets the response message sent with the response code.
void setChunkedStreamingMode(int chunklen) Enables streaming of an HTTP request body without internal buffering when content length is not known in advance.
void setFixedLengthStreamingMode(int contentlength) Enables streaming of an HTTP request body without internal buffering when content length is known in advance.
void setFixedLengthStreamingMode(long contentlength) Enables streaming of an HTTP request body without internal buffering when content length is not known in advance.
static void setFollowRedirects(boolean set) Sets whether HTTP redirects should be automatically followed by HttpURLConnection class.
void setInstanceFollowRedirects(boolean followRedirects) Sets whether HTTP redirects should be automatically followed by the instance of HttpURLConnection class.
void setRequestMethod(String method) Sets the method for the URL request, such as GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.
abstract boolean usingProxy() Indicates if the connection is going through a proxy.

Getting the HttpURLConnection Object

Use the openConnection() method of the URL class to get a URLConnection object, then cast it to HttpURLConnection:

Syntax

public URLConnection openConnection() throws IOException {}

URL url = new URL("http://www.tutorialsarena.com/java-tutorial");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();

Java HttpURLConnection Example

Syntax

import java.io.*;
import java.net.*;

public class HttpURLConnectionDemo {
public static void main(String[] args) {
try {
    URL url = new URL("http://www.google.com");
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    for (int i = 1; i <= 8; i++) {
        System.out.println(huc.getHeaderFieldKey(i) + " = " + huc.getHeaderField(i));
    }
    huc.disconnect();
} catch (Exception e) {
    System.out.println(e);
}
}
}
Output

Date = Thu, 22 Jul 2021 18:08:17 GMT
Server = Apache
Location = https://www.google.com
Cache-Control = max-age=2592000
Expires = Sat, 21 Aug 2021 18:08:17 GMT
Content-Length = 248
Keep-Alive = timeout=5, max=1500
Connection = Keep-Alive