HttpURLConnection class in Java

java.net.HttpURLConnection

A URLConnection with support for HTTP-specific features.

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.

The HTTP protocol handler has a few settings that can be accessed through System Properties. This covers Proxy settings as well as various other settings.

If the automatic redirection is enabled, and this request is redirected to another destination, then the caller must also have permission to connect to the redirected host/URL.

Some methods of HttpURLConnection class

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.

HttpURLConnection usingProxy() in Java

usingProxy(): This method is available in the java.net.HttpURLConnection class of Java.

Syntax:

boolean java.net.HttpURLConnection.usingProxy()

This method indicates if the connection is going through a proxy.

This method returns true if the connection is known to be going or has gone through proxies, and returns false if the connection will never go through a proxy or if the use of a proxy cannot be determined.

Parameters: NA

Returns: a boolean indicating if the connection is using a proxy.

Exceptions: NA

Approach

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionusingProxy {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        System.out.println(httpURLConnection.usingProxy());

    }
}

Output:

false


Some other methods of HttpURLConnection

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.

HttpURLConnection setRequestMethod(String) in Java

setRequestMethod(String): This method is available in the java.net.HttpURLConnection class of Java.

Syntax:

void java.net.HttpURLConnection.setRequestMethod(String method) throws ProtocolException

This method takes one argument. This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

The default method is GET.

Parameters: One parameter is required for this method.

method: the HTTP method.

Returns: NA

Throws:

1. ProtocolException - if the method cannot be reset or if the requested method isn't valid for HTTP.

2. SecurityException - if a security manager is set and the method is  "TRACE", but the "allowHttpTrace" NetPermission is not granted.

Approach 1: When no exception

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionsetRequestMethod {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        String method = "GET";
        httpURLConnection.setRequestMethod(method);
        System.out.println("Successfully setRequestMethod");

    }
}

Output:

Successfully setRequestMethod


Approach 2: ProtocolException 

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionsetRequestMethod {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        String method = "HELLO";
        httpURLConnection.setRequestMethod(method);
        System.out.println("Successfully setRequestMethod");

    }
}

Output:

Exception in thread "main" java.net.ProtocolException: Invalid HTTP method: HELLO at java.base/java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:487) at java.base/sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:571) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:344) at com.HttpURLConnection.HttpURLConnectionsetRequestMethod.main(HttpURLConnectionsetRequestMethod.java:13)


Some other methods of HttpURLConnection

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.

HttpURLConnection setInstanceFollowRedirects(boolean) in Java

setInstanceFollowRedirects(boolean): This method is available in the java.net.HttpURLConnection class of Java.

Syntax:

void java.net.HttpURLConnection.setInstanceFollowRedirects(boolean followRedirects)

This method takes one argument. This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

The default value comes from followRedirects, which defaults to true.

Parameters: One parameter is required for this method.

followRedirects: a boolean indicating whether or not to follow HTTP redirects.

Returns: NA

Exceptions: NA

Approach

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionsetInstanceFollowRedirects {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        boolean followRedirects = true;
        httpURLConnection.setInstanceFollowRedirects(followRedirects);
        System.out.println("Successfully setInstanceFollowRedirects");

    }
}

Output:

Successfully setInstanceFollowRedirects


Some other methods of HttpURLConnection

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.

HttpURLConnection.setFollowRedirects(boolean) in Java

HttpURLConnection.setFollowRedirects(boolean): This method is available in the java.net.HttpURLConnection class of Java.

Syntax:

void java.net.HttpURLConnection.setFollowRedirects(boolean set)

This method takes one argument. This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

True by default. Applets can not change this variable.

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed.

This could result in a SecurityException.

Parameters: One parameter is required for this method.

set: a boolean indicating whether or not to follow HTTP redirects.

Returns: NA

Throws:

1. SecurityException - if a security manager exists and its checkSetFactory method doesn't allow the operation.

Approach

Java

package com.HttpURLConnection;

import java.net.HttpURLConnection;

public class HttpURLConnectionsetFollowRedirects {
    public static void main(String[] args) {

        boolean set = true;
        HttpURLConnection.setFollowRedirects(set);
        System.out.println("Successfully setFollowRedirects");
    }
}

Output:

Successfully setFollowRedirects


Some other methods of HttpURLConnection

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.

HttpURLConnection setFixedLengthStreamingMode(long) in Java

setFixedLengthStreamingMode(long): This method is available in the java.net.HttpURLConnection class of Java.

Syntax:

void java.net.HttpURLConnection.setFixedLengthStreamingMode(long contentLength)

This method takes one argument. This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

An exception will be thrown if the application attempts to write more data than the indicated content length, or if the application closes the OutputStream before writing the indicated amount.

Parameters: One parameter is required for this method.

contentLength: The number of bytes that will be written to the OutputStream.

Returns: NA

Throws:

1. IllegalStateException - if URLConnection is already connected or if a different streaming mode is already enabled.

2. IllegalArgumentException - if a content length less than zero is specified.

Approach 1: When no exception

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionsetFixedLengthStreamingMode2 {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        long contextLength = 4000;
        httpURLConnection.setFixedLengthStreamingMode(contextLength);
        System.out.println("Successfully setFixedLengthStreamingMode");

    }
}

Output:

Successfully setFixedLengthStreamingMode


Approach 2: IllegalArgumentException 

Java

package com.HttpURLConnection;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionsetFixedLengthStreamingMode2 {
    public static void main(String[] args) throws IOException {
        URL url =
new URL("https://beingcodeexpert.blogspot.com/");
        HttpURLConnection httpURLConnection =
(HttpURLConnection) url.openConnection();

        long contextLength = -4000;
        httpURLConnection.setFixedLengthStreamingMode(contextLength);
        System.out.println("Successfully setFixedLengthStreamingMode");

    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: invalid content length at java.base/java.net.HttpURLConnection.setFixedLengthStreamingMode(HttpURLConnection.java:254) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.setFixedLengthStreamingMode(HttpsURLConnectionImpl.java:494) at com.HttpURLConnection.HttpURLConnectionsetFixedLengthStreamingMode2.main(HttpURLConnectionsetFixedLengthStreamingMode2.java:13)


Some other methods of HttpURLConnection

HttpURLConnection Status CodeSome of the status codes of HttpURLConnection. example HttpURLConnection.HTTP_ACCEPTED, HttpURLConnection.HTTP_BAD_GATEWAY, etc.

disconnect()This method indicates that other requests to the server are unlikely in the near future.

getErrorStream()This method returns the error stream if the connection failed but the server sent useful data nonetheless.

HttpURLConnection.getFollowRedirects()This method returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

getHeaderField(int)This method returns the value for the nth header field.

getHeaderFieldDate(String, long)This method Returns the value of the named field parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT represented by the named field.

getHeaderFieldKey(int)This method returns the key for the nth header field.

getInstanceFollowRedirects()This method returns the value of this HttpURLConnection instanceFollowRedirects field.

getPermission()This method returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

getRequestMethod()This method gets the request method.

getResponseCode()This method gets the status code from an HTTP response message.

getResponseMessage()This method gets the HTTP response message, if any, returned along with the response code from a server.

setAuthenticator(Authenticator)This method supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.If no authenticator is supplied, the default authenticator will be used.

setChunkedStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is not known in advance.

setFixedLengthStreamingMode(int)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

setFixedLengthStreamingMode(long)This method is used to enable the streaming of an HTTP request body without internal buffering when the content length is known in advance.

HttpURLConnection.setFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setInstanceFollowRedirects(boolean)This method sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setRequestMethod(String)This method sets the method for the URL request, as one of •GET •POST •HEAD •OPTIONS •PUT •DELETE •TRACE are legal, subject to protocol restrictions.

usingProxy()This method indicates if the connection is going through a proxy.