HttpURLConnection
HttpURLConnection
Protocol
It is a standard set of rules that allow electronic devices to communicate with each other.
The http protocol
The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide Web. The http is a TCP/IP based communication protocol that is used to deliver data on the World Wide Web.
The http protocol is the client server-based architecture where web browsers, robots and search engines, etc., acts like http clients, and the server acts as a server.
The http client requests a URL, which is having a protocol version, a domain name followed by the file or directories name. The http server responds, including the message’s protocol version and a success or error code, followed by a MIME-like message containing server information, entity meta-information, and possible entity-body content.
HttpURLConnection
It is a http specific URLConnection. It works for http protocol only. You can get information about any http URL such as header information, status code, response code by using the HttpURLConnection class.
Features:
- It is an abstract class directly extending from the URLConnection class.
- It is a http specific URLConnection, works for http protocol only. It extends all the functionality of its parent class with additional http related features.
Getting object of HttpURLConnection class:
1. public URLConnection openConnection()throws IOException() { //returns the object of URLConnection class. } 2. By typecasting it to HttpURLConnection type as given we get object of the HttpURLConnection. URL url=new URL("http://www.javatpoint/java-tutorial"); HttpURLConnection hcon=(HttpURLConnection)url.openConnection();
Explanation:
- Creating the URL object by using the
URL url=new URL(“http://www.javatpoint/java-tutorial”);
- Obtain a URLConnection object by calling openConnection() of the URL class and casting the result to HttpURLConnection.
HttpURLConnection hcon=(HttpURLConnection)url.openConnection();
Methods in HttpURLConnection class:
Method | Description |
public boolean getInstanceFollowRedirects() | It returns true or false depending on the automatic instance redirection set or not. |
public InputStream getErrorStream() | It gets the error stream if the server cannot be connected or some error occurred. It can contain information about how to fix the error. |
public Permission getPermission() | It returns permission required to connect to the server. |
public void setChunkedStreamingMode(int n)throws IllegalStateException | This mode is used when the content length is not known. Instead of creating a buffer of fixed length and writing it to the server, content is broken into chunks and then written. Not all servers support this mode. |
public boolean usingProxy() | It returns true if the connection is established using a proxy, else false. |
public void disconnect () | It indicates that other requests to the server are disconnected. |
public static boolean getFollowRedirects() | It returns true or false depending upon if there is an automatic redirection or not. |
public void setFollowRedirects(boolean b) | It sets whether a 3xx response code requests redirect automatically or not. |
public void setFixedLengthStreamingMode(long n/int n)throws IllegalStateException | It used to set the length of a content written on the output stream if it knows in advance. |
public String getHeaderField() | It returns the n header field, or null if it does not exist. It overrides the getHeaderField method of URLConnection class. |
public String getResponseMessage() | It retrieves the response message. |
protected String getRequestMethod() | It returns the request method. |
protected void setRequestMethod(String method)throws ProtocolException | It is used to set the request method. The default is GET. |
protected int getResponseCode() | To retrieve the response status from the server. |
Example 1: To read the header information
import java.io.*; import java.net.*; public class httpcon1 { public static void main(String s[]) { try { URL url=new URL("http://www.javatpoint.com/java-tutorial"); HttpURLConnection h1=(HttpURLConnection)url.openConnection(); for(int i=1;i<=8;i++) { System.out.println(h1.getHeaderFieldKey(i)+"="+h1.getHeaderField(i)); } h1.disconnect(); }catch(Exception e){ System.out.println(e); }} }
The output of the above program:

Example 2: To use http accessing webpage.
To access http client resources via the HTTP protocol. The URL class provides the address to a web resource. HttpURLConnection allows to create an InputStream. By using the InputStream, you can use it to read the file.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class httpcon1{ private static final String line = System.getProperty("line.separator"); public static void main(String s1[]) { try { URL url = new URL("https://www.google.com/"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String readStream = readStream(con.getInputStream()); System.out.println(readStream); } catch (Exception e) { e.printStackTrace(); } } private static String readStream(InputStream in) { StringBuilder sb = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) { String nextLine = ""; while ((nextLine = reader.readLine()) != null) { sb.append(nextLine +line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
Explanation of the above program:
- The URL class is used to create the URL object.
- The openConnection() of the URL is to create an object of the URLConnection, which is typecasted to HttpURLConnection.
- The StringBuilder in Java represents a mutable sequence of characters. The StringBuilder class differs from the StringBuffer class based on synchronization. It is recommended to use this class in comparison with StringBuilder as it will be faster under most implementations. An instance of StringBuilder is not safe for use by multiple threads.
- An InputStreamReader changes byte streams to character streams. It reads bytes and converts them into characters. A BufferedReader is a class in Java that reads text from a character-input stream, buffering characters for the reading of lines and arrays. The readLine() method of the BufferedReader class reads a line of text.
The output of the above program:

Example 3: To get the return code from a webpage.
Returns code is a standardized code that is returned by the webserver if some specific situation has occurred.
The commonly used return codes are:
Return code | Explanation |
200 | ok |
301 | Permanent redirect to another webpage |
400 | Bad request |
404 | Not found |
import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class httpcon1 { public static void main(String s1[]) throws IOException { String urltext = "https://www.facebook.com/"; URL url = new URL(urltext); int responseCode = ((HttpURLConnection) url.openConnection()).getResponseCode(); System.out.println(responseCode); } }
The output of the above:

Example 4: To describe the kind of web resource.
The internet media type(MIME), describes the kind of web resource.
import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class httpcon1 { public static void main(String s1[]) throws IOException { String urltext = "https://www.facebook.com/"; URL url = new URL(urltext); String contentType = ((HttpURLConnection) url.openConnection()).getContentType(); System.out.println(contentType); } }
The output of the program:
