The Price of all “Rest with Spring” course packages will increase by $50 next Friday:


1. Overview

In this quick tutorial, we’re going to present a way of performing HTTP requests in Java — by using the built-in Java class HttpUrlConnection.

2. HttpUrlConnection

The HttpUrlConnection class allows us to perform basic HTTP requests without the use of any additional libraries. All the classes that are needed are contained in the package.

The disadvantages of using this method are that the code can be more cumbersome than other HTTP libraries, and it does not provide more advanced functionalities such as dedicated methods for adding headers or authentication.

3. Creating a Request

A HttpUrlConnection instance is created by using the openConnection() method of the URL class. Note that this method only creates a connection object, but does not establish the connection yet.

The HttpUrlConnection class is used for all types of requests by setting the requestMethod attribute to one of the values: GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.

Let’s create a connection to a given url using GET method:

URL url = new URL("");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

4. Adding Request Parameters

If we want to add parameters to a request, we have to set the doOutput property to true, then write a String of the form param1=value&param2=value to the OutputStream of the HttpUrlConnection instance:

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

DataOutputStream out = new DataOutputStream(con.getOutputStream());

To facilitate the transformation of the parameter Map, we have written a utility class called ParameterStringBuilder containing a static method getParamsString() that transforms a Map to a String of the required format:

public class ParameterStringBuilder {
    public static String getParamsString(Map<String, String> params) 
      throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();

        for (Map.Entry<String, String> entry : params.entrySet()) {
          result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
          result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

        String resultString = result.toString();
        return resultString.length() > 0
          ? resultString.substring(0, resultString.length() - 1)
          : resultString;

5. Setting Request Headers

Adding headers to a request can be achieved by using the setRequestProperty() method:

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

To read the value of a header from a connection, we can use the getHeaderField() method:

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

6. Configuring Timeouts

HttpUrlConnection class allows setting the connect and read timeouts. These values define the interval of time to wait for the connection to the server to be established or data to be available for reading.

To set the timeout values we can use the setConnectTimeout() and setReadTimeout() methods:


In the example above, we have set both timeout values to 5 seconds.

7. Handling Cookies

The package contains classes that ease working with cookies such as CookieManager and HttpCookie.

First, to read the cookies from a response, we can retrieve the value of the Set-Cookie header and parse it to a list of HttpCookie objects:

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

Next, we will add the cookies to the cookie store:

cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));

Let’s check if a cookie called username is present, and if not, we will add it to the cookie store with a value of “john”:

Optional<HttpCookie> usernameCookie =
  .findAny().filter(cookie -> cookie.getName().equals("username"));
if (usernameCookie == null) {
    cookieManager.getCookieStore().add(null, new HttpCookie("username", "john"));

Finally, to add the cookies to the request, we need to set the Cookie header, after closing and reopening the connection:

con = (HttpURLConnection) url.openConnection();

  StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));

8. Handling Redirects 

We can enable or disable automatically following redirects for a specific connection by using the setInstanceFollowRedirects() method with true or false parameter:


It is also possible to enable or disable automatic redirect for all connections:


By default, the behavior is enabled.

When a request returns a status code 301 or 302, indicating a redirect, we can retrieve the Location header and create a new request to the new URL:

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();

9. Reading the Response

Reading the response of the request can be done by parsing the InputStream of the HttpUrlConnection instance.

To execute the request we can use the getResponseCode(), connect(), getInputStream() or getOutputStream() methods:

int status = con.getResponseCode();

Finally, let’s read the response of the request and place it in a content String:

BufferedReader in = new BufferedReader(
  new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {

To close the connection, we can use the disconnect() method:


10. Conclusion

In this article, we have shown how we can perform HTTP requests using the HttpUrlConnection class. The full source code of the examples can be found over on GitHub.

The Price of all “Rest with Spring” course packages will increase by $50 next Friday:


Sort by:   newest | oldest | most voted
Slava Semushin

> String contentType = con.getHeaderField(“Content-Type”);

For getting Content-Type, I’d rather use dedicated getContentType() method.

> Finally, let’s read the response of the request and place it in a content String:

The example could be improved by using try-with-resources. In the current state, there will be a resource leak if exception occurs.

> The full source code of the examples can be found over on GitHub (

I don’t see the example of using HttpURLConnection there.

Loredana Crusoveanu

Hi Slava.

My responses in order:

– true, but the getHeaderField shows a more general way to get the value of any Header; Content-Type is just used as an example

– the try statements were avoided to not distract from the usage of the HttpUrlConnection class. In code, the exceptions would have to be treated since they are checked

– sorry, the link is wrong – it should point to core-java instead of libraries project. Will update, thanks.