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

The HttpURLConnection is an important class in java.net package which allows you to send an HTTP request from Java program. By using this you can send any kind of HTTP request e.g. GET, POST, PUT, DELETE, HEAD etc. It also provides several methods to configure your HTTP requests e.g. it allows you to add headers, add request parameters, attaching cookie, configuring timeout, handling redirects and so on. A 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 Java world, knowing how to do it without using 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 example of HttpURLConnection which will teach you how to send HTTP request from 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.


And If you want to learn Java from Scratch, I suggest you check out The Complete Java MasterClass course, most comprehensive and up-to-date course, which is recently updated for Java 11 as well.




HttpURLConnection Examples in Java

Here are some of the fundamentals code examples of using HttpURLConnection class in Java


1) 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 e.g. 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 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 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) Send a POST request
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 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 POST request is the most appropriate request.  See Complete Java Masterclass learn more about sending an HTTP request from Java.

7 Examples of HttpURLConnection in Java




3) Check the Response Code
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's not send already.

Here is the code to retrieve resposne 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 getRequestProperty() method, which accepts header name and return value e.g.

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 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 paramters 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 HttpClient library has better support for adding request parameter to HTTP request.  See Java In-Depth: Become a Complete Java Engineer! to learn more about dealing request parameters for HTTP request in Java.




6) Dealing with Cookies
You can use the HttpCookie and CookiManager classes from java.net package to both send and receive Cookie from Java program. You can retrieve the value of header "Set-Cookie" to retrieve cookies from 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 retreive stored cookies to attach with outgoing request. Just set the "Cookie" header with the values as Cookies retrieved from 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 thing to consider while making HTTP request 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 class for JDK and every Java developer should be aware of that. You might not need this in your project, especially if you are using HttpClient library but you must know that this is what JDK provides and every other third-party library will used it provide syntactic sugar over it.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues.

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

No comments:

Post a Comment