How to Use java.net.URLConnection to Fire and Handle HTTP Requests?

How to Use java.net.URLConnection to Fire and Handle HTTP Requests?

java.net.URLConnection in Java is used for handling HTTP requests in Java. With this class, you can send HTTP requests, manage connections, and also process responses, without using the external libraries

Whether you’re new to HTTP in Java or looking for an efficient solution to handle HTTP requests, we’ll guide you in using URLConnection to make HTTP requests, handle responses, and manage connections.

Table of Contents:

What is URLConnection in Java?

The URLConnection in Java is used to connect to the Internet. It is an abstract class that allows Java applications to talk to a resource or to read the data from a URL. It acts as a bridge between your Java code and the Internet.

In this abstract class, we can connect to a website, download data like HTML or files, and send data to a server.

Features of the URLConnection class

  1. It is an abstract class and provides communication between the Java program and a URL resource.
  2. It has 2 main subclasses
    • HttpURLConnection: For handling HTTP connections.
    • JarURLConnection: For accessing JAR file resources.
  3. It supports different protocols like FTP and file URLs.
  4. It can read and write a resource.

Steps to Establish a URL Connection in Java

To establish a connection using URLConnection in Java, follow these steps:

1. Create a URL Object

Define the URL of the resource you want to connect to.

URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");  

2. Open a Connection

Use the openConnection() method to get a URLConnection object.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

3. Establish the Connection

Use connect() to start the connection

conn.connect();

4. Read Data from the Server

Use an InputStream to read the response from the server. If sending data, use an OutputStream.

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line); 
}

5. Close the Connection

If using streams, always close the connection to free up the resources.

reader.close();
conn.disconnect();
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

What is HttpURLConnection?

The HttpURLConnection is a Java class used to communicate between an application and a URL. It is used to read and write data.

It has two components:

1. Client-Side / Request

Sends a request to the server using HTTP methods like GET and POST. The request from the client is sent to the server. It uses methods like GET, POST, etc, and sends the data to the server side.

2. Server Side / Response 

The request is sent by the client and received by the server, and according to that, the response is sent back to the client. 

Server Side - Response

Making an HTTP GET Request (Firing a Request)

The GET method is used to retrieve the data from the server. They do not send any optional data with the request body. During GET requests, multiple requests to the same URL can return the same result as long as the data remains unchanged on the server.

Example:

Java

Output:

Making an HTTP GET Request

Explanation: In the above Java program, the data is obtained from an API. It first defines the URL and opens an HTTP connection. The request method is set to “GET”, due to which no additional data will be sent in the request body. The program sets connection timeouts and checks the server’s response code. If the response is successful, it reads and prints the data using a BufferedReader. The response contains JSON data from the server.

Unlock Your Future in Java
Start Your Java Journey for Free Today
quiz-icon

Making a POST Request (Handling a Request)

The Java HTTP GET POST request is used to send data to the server. The data here is sent in the request body.

 It is also used to create a new resource.

Example:

Java

Output:

Making a POST Request

Explanation: In the above Java program, the program sends the data to the server. It makes a connection with the API and sets the request method to “POST”. Java HTTP GET POST also have headers to show JSON data, Content-Type: application/json. After sending a request, it checks the response code; if it is 201, it is successful, after which it reads the response from the server. Hence, the server data is changed by adding new information.

Methods of the java.net.HttpURLConnection Class in Java

There are various methods in the java.net.HttpURLConnection class in Java, which are used to perform different tasks related to HTTP communication. Some of the commonly used methods are as follows:

Method Action Performed
disconnect() Indicates the connection to the server is no longer needed and releases resources
getErrorStream() Retrieves an input stream for reading server errors
getFollowRedirects() Determines if automatic redirection is enabled for HTTP responses (3xx status codes)
getHeaderField(String name) Gets the value of a specific HTTP header field by name
getInstanceFollowRedirects() Checks if automatic redirection is enabled for this connection instance
getPermission() Retrieves permission required to access the URL resource
getResponseCode() Returns the HTTP response status code (e.g., 200, 404)
getResponseMessage() Provides the server message for the HTTP status code (e.g., “OK” for 200)
getRequestMethod() Returns the HTTP request method used (e.g., “GET”, “POST”)
setInstanceFollowRedirects(boolean followRedirects) Configures automatic HTTP redirect following for this connection instance
setRequestMethod(String method) Sets the HTTP request method (e.g., “GET”, “POST”, “PUT”, “DELETE”)
setFixedLengthStreamingMode(int length) Specifies content length when known in advance for output streaming
setFollowRedirects(boolean followRedirects) Controls automatic following of HTTP 3xx redirect responses
setChunkedStreamingMode(int chunkSize) Configures chunk size for streaming large data outputs
usingProxy() Returns true if the connection uses a proxy server

Common Pitfalls for Using java.net.URLConnection to Fire and Handle HTTP Requests

While java.net.URLConnection simplifies Java HTTP requests, developers often encounter these pitfalls:

  1. Thread Blocking: Synchronous calls block threads; consider async alternatives like completable Future for scalability.
  2. Forgetting Timeouts: Not setting setConnectTimeout() or setReadTimeout() can cause indefinite hangs.
  3. Not Handling Redirects: HTTP 3xx responses require manual handling unless setFollowRedirects(true) is configured.
  4. Ignoring Response Codes: Always check getResponseCode() before processing responses (e.g., 404 errors).
  5. Resource Leaks: Failing to close InputStream/OutputStream or disconnect  HttpURLConnection drains resources.

Alternatives to HttpURLConnection

While java.net.URLConnection works for basic HTTP requests in Java, consider these libraries for advanced use:

1. Apache HttpClient: Supports connection pooling, async requests, and detailed

metrics.javaCopyDownloadCloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet("https://api.example.com");

2. OkHttp: Efficient for modern apps

(HTTP/2, WebSocket support).javaCopyDownloadOkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build();

3. Retrofit: Turns REST APIs into Java interfaces

(uses OkHttp under the hood).javaCopyDownloadpublic interface ApiService { @GET("posts/{id}") Call<Post> getPost(@Path("id") int postId); }

Why Switch?

  • Better performance and thread safety.
  • Simplified syntax for Java HTTP GET/POST.
  • Built-in JSON parsing (e.g., Retrofit + Gson).

Handling Errors and Timeouts in Java HTTP Requests

Robust error handling is critical for reliable HTTP request handling in Java:

1. Timeout Configuration

HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
conn.setConnectTimeout(5000); // 5-second connection timeout  
conn.setReadTimeout(10000); // 10-second read timeout  

2. Error Streams

For non-2xx responses (e.g., 400/500), read errors via getErrorStream():

if (responseCode >= 400) {  
  try (BufferedReader errorReader = new BufferedReader(  
    new InputStreamReader(conn.getErrorStream()))) {  
    // Log or process error  
  }  
}  

3. Retry Logic

Implement retries for transient failures (e.g., 503 errors):

int maxRetries = 3;  
while (maxRetries-- > 0 && responseCode != 200) {
conn = (HttpURLConnection) url.openConnection();
// Re-attempt request
}

Other than Java’s built-in library for the HttpURLConnection, there are many third-party libraries. Some of these are:

1. Apache HTTPClient

It is a popular, open-source Java library used for building HTTP-based client applications. They are used for authentication and handling requests/responses.

2. OkHttp

It was developed by Square. OkHttp is a powerful and efficient HTTP client known for its speed. It gives better performance.

3. Retrofit

It is built on top of OkHttp. It is a REST client for both Java and Android. It converts HTTP APIs into Java interfaces and makes API calls readable and maintainable. It also supports JSON parsing, authentication, and asynchronous requests.

For the Maven projects, one has to add the dependency on it in the pom.xml file.

Feature Apache HttpClient OkHttp Retrofit
Ease of Use Medium complexity Easy to implement Very easy with annotations
Performance Fast processing Faster with SPDY support Fast (built on OkHttp)
Connection Pooling Yes Yes Yes
Async Support No Yes (Callbacks) Yes (RxJava/Coroutines)
JSON Handling Manual parsing Manual parsing Automatic conversion
Best Use Case Enterprise applications Android development REST API clients

JSON Parsing Example with HttpURLConnection

After making a Java HTTP GET/POST request, parse JSON responses using org.json or Gson:

Example: Parse GET Response

import org.json.JSONObject;  
// ... (GET request code)  
if (responseCode == 200) {  
  StringBuilder response = new StringBuilder();  
  String line;  
  while ((line = reader.readLine()) != null) {  
    response.append(line);  
  }  
  JSONObject json = new JSONObject(response.toString());  
  System.out.println("Title: " + json.getString("title"));  
}  

POST with JSON Payload

For Java HTTP POST requests, serialize data to JSON:

String jsonInputString = new JSONObject()  
.put("title", "Hello")
.put("body", "Test POST")
.toString();
// ... (send via OutputStream)

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

From above, we learnt how to use URLConnection in Java to send and receive data from websites. We have learned how to connect to a URL, get data (GET request), send data (POST request), and read responses. We have also looked at easy-to-use libraries like Apache HttpClient, OkHttp, and Retrofit, which can help make web requests easier and faster.

To learn more about this topic, you can refer to our Java Course and also prepare for your interview with industry-prepared Java Interview Questions.

How to Use java.net.URLConnection to Fire and Handle HTTP Requests? – FAQs

Q1. What is the difference between HttpURLConnection and URLConnection in Java?

The URLConnection class provides an API for generic URLs, and its subclass, HttpURLConnection, provides additional support for HTTP-specific features.

Q2. What are the four types of Java HTTP request methods?

The primary or most commonly used Java HTTP request are POST, GET, PUT, and DELETE.

Q3. How to pass query parameters in HttpURLConnection?

Call the setRequestProperty() method on the HttpURLConnection instance to set request header values, such as “User-Agent” and “Accept-Language,” etc.

Q4. How to close HttpURLConnection in Java?

Once the response body has been read, the HttpURLConnection should be closed by calling disconnect().

Q5. How to send JSON body in URL?

You must encode a JSON object as a string and include it in the query string portion of the URL to pass it in a URL.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner