Backend Development 8 min read

How to Perform HTTP Requests in Java Using HttpURLConnection

This article demonstrates how to implement HTTP requests in Java using the built-in HttpURLConnection class, covering request creation, adding parameters, setting headers, handling timeouts, cookies, redirects, and reading responses, including error handling, with complete code examples.

IT Services Circle
IT Services Circle
IT Services Circle
How to Perform HTTP Requests in Java Using HttpURLConnection

During a recent interview an interviewer asked the candidate to implement an HTTP request in Java. This article shows how to fulfill that requirement using Java's built‑in HttpURLConnection class.

HttpURLConnection

The HttpURLConnection class allows basic HTTP requests without any external libraries; all required classes are part of the java.net package. Its drawback is more verbose code compared with third‑party HTTP libraries and the lack of dedicated methods for advanced features such as custom headers or authentication.

Create a Request

Use URL.openConnection() to obtain an HttpURLConnection instance. The connection object is created but not yet opened. Set the request method (GET, POST, etc.) before connecting.

URL url = new URL("https://www.javanorth.cn");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");

Add Request Parameters

To send parameters, enable output with setDoOutput(true) and write a URL‑encoded string to the connection's OutputStream . The helper class ParameterStringBuilder converts a Map<String, String> into the required query string.

Map
parameters = new HashMap<>();
parameters.put("param1", "val");

con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
public class ParameterStringBuilder {
    public static String getParamsString(Map
params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        for (Map.Entry
entry : params.entrySet()) {
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            result.append("&");
        }
        String resultString = result.toString();
        return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
    }
}

Set Request Headers

Use setRequestProperty() to add custom headers, for example setting the content type to JSON.

con.setRequestProperty("Content-Type", "application/json");

To read a header value from the response, call getHeaderField() .

String contentType = con.getHeaderField("Content-Type");

Configure Timeouts

Set connection and read timeouts with setConnectTimeout() and setReadTimeout() . In the example both are set to 5000 ms.

con.setConnectTimeout(5000);
con.setReadTimeout(5000);

Handle Cookies

The java.net package provides CookieManager and HttpCookie for cookie handling. Retrieve the Set‑Cookie header, parse it, and store cookies in the manager.

String cookiesHeader = con.getHeaderField("Set-Cookie");
List
cookies = HttpCookie.parse(cookiesHeader);

Add the cookies to the store and, if a specific cookie (e.g., username ) is missing, create it.

cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));
Optional
usernameCookie = cookies.stream()
    .filter(cookie -> cookie.getName().equals("username"))
    .findAny();
if (usernameCookie == null) {
    cookieManager.getCookieStore().add(null, new HttpCookie("username", "javanorth"));
}

After reconnecting, send the accumulated cookies in the request header.

con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));

Handle Redirects

Enable or disable automatic redirect following per connection with setInstanceFollowRedirects() , or globally with HttpURLConnection.setFollowRedirects() . When a 301/302 response is received, manually retrieve the Location header and open a new connection.

con.setInstanceFollowRedirects(false);
// or globally
HttpURLConnection.setFollowRedirects(false);

if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
    String location = con.getHeaderField("Location");
    URL newUrl = new URL(location);
    con = (HttpURLConnection) newUrl.openConnection();
}

Read Response

Obtain the response code, then read the response body from the appropriate stream. For successful responses use getInputStream() ; for error responses use getErrorStream() .

int status = con.getResponseCode();
Reader streamReader = null;
if (status > 299) {
    streamReader = new InputStreamReader(con.getErrorStream());
} else {
    streamReader = new InputStreamReader(con.getInputStream());
}
BufferedReader in = new BufferedReader(streamReader);
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
    content.append(inputLine);
}
in.close();

Finally, close the connection with disconnect() .

con.disconnect();

Summary

This article illustrated a complete workflow for performing HTTP requests in Java using HttpURLConnection , including request construction, parameter encoding, header manipulation, timeout configuration, cookie management, redirect handling, and response processing for both successful and error cases.

backendJavaHTTPnetworkinghttpurlconnection
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.