7 Examples of HttpURLConnection in Java - Sending GET and POST Request [Tutorial]

If you want to learn how to send GET and POST requests from the Java program then you have come to the right place. Earlier, I have shared free Java Courses for beginners, and today, I am going to show you how to use HttpURLConnection class in Java to send HTTP requests to the server.  The HttpURLConnection is an important class in the java.net package which allows you to send an HTTP request from a Java program. By using this class you can send any kind of HTTP request like GET, POST, PUT, DELETE, HEAD, etc to the server and call REST APIs. 

It also provides several methods to configure your HTTP requests like it allows you to add headers, add request parameters, attach cookies, configure a timeout, handle redirects, and so on. Good knowledge of this class is important for Java developers working on both core Java and Java web application.

Sending HTTP request is quite common in today's connected world and even though a lot of powerful, third-party libraries e.g. Apache HttpClient exists in the Java world, knowing how to do it without using a third-party library always matters.

If you know this class, you can easily write some unit tests for your REST API like you can verify response code, headers, and JSON payload.

In this article, I am going to show you some of the basic examples of HttpURLConnection which will teach you how to send an HTTP request from a Java program and configure it according to your need.

Though, if you are not familiar with Socket programming in Java then I also suggest you check the Java: Socket Programming Simplified, a free course on Udemy If you are a beginner and want to learn Java from Scratch, I suggest you check out The Complete Java MasterClass course, the most comprehensive and up-to-date course, which is recently updated for Java 11 as well.




7 HttpURLConnection Examples in Java

Here are some of the fundamentals code examples of using HttpURLConnection class in Java. You can follow them to learn how to send HTTP requests from Java, how to set headers and cookies, and how to read response code from HTTP response right from your Java program. 

1. How to Send a simple GET request

You can send an HTTP request by just creating a URL object with the actual URL and then creating an HttpURLConnection from that. Btw, the actual request is not sent until you perform some operation like reading a response code or reading data from InputStream.

Here is a simple code to send the most simple GET request to access your Github profile in the Java program:

public class Hello {

public static void main(String args[]) throws IOException {

 URL url = new URL("https://api.github.com/users/google");
 HttpURLConnection con = (HttpURLConnection) url.openConnection();
 con.setRequestMethod("GET");

 BufferedReader in = new BufferedReader(new InputStreamReader(
 con.getInputStream()));
 String inputLine;
 while ((inputLine = in.readLine()) != null) {
   System.out.println(inputLine);
 } 


in.close();
}
}

In this code, we are reading the response line by line and closing it once we are done with reading the response. Remember, the HttpURLConnection object can be used only to send one quest and that's why you must close it after using it.



2. How to Send a POST request from Java Program

The HttpConnection class also allows you to send a POST request, and not just POST by any HTTP method e.g. PUT, DELETE, or PATCH. All you need to do is call the setRequestMethod("POST") from HttpURLConnection with the appropriate method name e.g. POST to send a POST request.

Here is the code:
URL url = new URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");

Remember, if you want to send Request parameters in the body, then a POST request is the most appropriate request.  See The Complete Java Masterclass to learn more about sending an HTTP request from Java.

7 Examples of HttpURLConnection in Java



3. How to Check the Response Code in Java

Checking the response code is very easy while using HttpURLConnection, you can just call the getResponseCode() method and it will return the error or response code as int. It will also send the request to the server if it does not send it already.

Here is the code to retrieve response code in Java:
int code = con.getResponseCode();

If you remember, code in the 200 range is for success, 400s are for client-side error and 500s are for server-side error.




4. Dealing with Headers

You can add headers into HTTP request by calling the setRequestProperty() method of HttpURLConnection as shown below:
con.setRequestProperty("Content-Type", "application/json");

In this case, we are setting the "Content-Type" header to "application/json" to indicate that the request is in JSON format. Similarly, you can also retrieve header values from HTTP response using the getRequestProperty() method, which accepts header name and returns a value like

String header = con.getRequestProperty("Content-Type");

You can use this to perform content negotiation while accessing REST APIs in Java.




5. Dealing with Request Parameters

You can also add Request or Query parameters to your HTTP request while using HttpURLConnection class, but it's a little bit tricky. You first need to enable the Connection object to write something on it and for that, you need to call the setDoOutput() method.

After that, you can get the OutputStream from HttpURLConnection and write query parameters into it in the form of param1=value&param2=value2&param3=value3.

Here is some code to add query parameters into an HTTP request using Java:
URL url = new URL("https://api.github.com/users/google");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
dos.writeChars("param1=value1&param2=value2");
dos.flush();
dos.close();

They could have done better with this but that's what you have when you are using HttpURLConnection. The alternative API provided by the HttpClient library has better support for adding request parameters to HTTP requests.  See these best free Java courses to learn more about dealing with request parameters for HTTP requests in Java.




6. How to deal with Cookies in Java [HttpCookie Example]

You can use the HttpCookie and CookiManager classes from the java.net package to both send and receive Cookie from the Java program. You can retrieve the value of header "Set-Cookie" to retrieve cookies from the response and parse them using HttpCookie class as shown below:
String cookie = con.getHeaderField("Set-Cookie");
List<HttpCookie> cookies = HttpCookie.parse(cookie);

Similarly, you can use the CookieManager class to store the cookies into CookiStore as well as retrieve stored cookies to attach with the outgoing requests. Just set the "Cookie" header with the values as Cookies retrieved from the store as shown below:
con.setRequestProperty("Cookie", 
   String.join(cookieManager.getCookieStore().getCookies(), ";"));

Btw, you need to disconnect and Open the HttpURLConnection again because you can only use it one time.


7. Configuring Timeouts

One of the important things to consider while making HTTP requests in production is setting up timeouts, obviously, you cannot wait forever for an HTTP request to complete.

Thankfully, HttpURLConnection allows you to configure timeouts while connecting as well as reading data using setConnectTimeout() and setReadTimeOut() method as shown below:
con.setConnectTimeout(10000);
con.setReadTimeout(10000);

The values specified are a time in milliseconds i.e. it will wait for 10 seconds while connecting to the server as well as while reading data from the server.

That's all about some of the basic examples of HttpURLConnection class in Java. As I said, it's one of the essential networking classes for JDK and every Java developer should be aware of that. You might not need this in your project, especially if you are using the HttpClient library but you must know that this is what JDK provides and every other third-party library will be used it provides syntactic sugar over it.



Other Java REST Web Service tutorials you may like
  • How to create a JDBC connection pool using Spring? (tutorial)
  • Top 5 courses to learn GraphQL for Beginners (courses)
  • The difference between REST and SOAP Web Services? (answer)
  • Top 10 REST Web Service Interview Questions (answer)
  • How to create a REST client using the Spring framework in Java? (tutorial)
  • 10 Free Courses to learn Spring Boot (Free Courses)
  • Spring HelloWorld Example using Dependency Injection (tutorial)
  • The difference between PUT vs POST in REST Web Service? (article)
  • Top 5 Courses to learn RESTFul Web Services in Java? (courses)
  • The difference between Idempotent and safe methods in HTTP? (answer)
  • How to convert a JSON array to a String array in Java? (tutorial)
  • 7 Best Courses to learn Spring Framework (best courses)
  • Top 5 Books to learn RESTful APIs and Web Services (books)
  • My Favorite Courses to learn Software Architecture (courses)
  • Top 10 Courses to learn Microservices for Java developers (courses)

Thanks for reading this article so far. If you like these HttpURLConnection examples in Java then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are new to the Java Programming world and want to learn more about Socket Programming in Java, I suggest you check the Java: Socket Programming Simplified, a free course on Udemy.

1 comment:

  1. how to set query parameter without directly sending it through url in get method

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.