HttpsUrlConnection REST API Call – Auth Token And Proxy Server

Introduction

In this example I am going to show you how to call REST APIs using javax.net.ssl.HttpsURLConnection. So, I am using plain Java code to send or receive data to or from the REST APIs. I am also going to show you how to send authentication token in the HTTP header. I am also going to show you how to use proxy server if you need to connect to proxy server during REST API call.

I am not going to build any REST API in this example and I will be using the online available REST APIs for testing purpose.

Related Post:

Prerequisites

Java 1.8+

Project Setup

I am creating maven based project and the following pom.xml file is used for this project:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>java-rest-call-httpsurlconnection</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>16</maven.compiler.source>
		<maven.compiler.target>16</maven.compiler.target>
	</properties>

	<dependencies>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</plugin>
		</plugins>
	</build>

</project>

Calling GET API

Here I am going to call REST API with GET request to fetch records from server. Let’s examine the following code snippets:

// Get a list of users
URL usersUrl = new URL("https://gorest.co.in/public/v1/users");

HttpsURLConnection conection = (HttpsURLConnection) usersUrl.openConnection();

// Set request method
conection.setRequestMethod("GET");

// Getting response code
int statusCode = conection.getResponseCode();

// If responseCode is 200, data fetch successful
if (statusCode == HttpsURLConnection.HTTP_OK) {
	BufferedReader in = new BufferedReader(new InputStreamReader(conection.getInputStream()));
	StringBuffer jsonResponseData = new StringBuffer();
	String readLine = null;

	// Append response line by line
	while ((readLine = in.readLine()) != null) {
		jsonResponseData.append(readLine);
	}

	in.close();
	// Print result in string format
	System.out.println("List of users: " + jsonResponseData.toString());
} else {
	System.out.println(statusCode);
}

In the above code snippets I am going to fetch all user information from the URL https://gorest.co.in/public/v1/users. The output response will be in JSON format.

First I have created a URL object usersUrl, then I have created HttpsUrlConnection object because I am fetching data from secured HTTPS protocol, so instead of HttpUrlConnection, I am using HttpsUrlConnection object.

Next I am setting the HTTP request method GET and checking the connection was successful or not to the remote URL connection. If status is 200 (OK), then I am getting data from the input stream of the connection using the following line:

BufferedReader in = new BufferedReader(new InputStreamReader(conection.getInputStream()));

Finally, reading the stream data as a string and appending to the StringBuffer (or StringBuilder) object:

StringBuffer jsonResponseData = new StringBuffer();
String readLine = null;

// Append response line by line
while ((readLine = in.readLine()) != null) {
	jsonResponseData.append(readLine);
}

The above code snippets fetch all user data from the given REST API URL. If you want to fetch single user information, then you have to pass user id as a path parameter in the URL, for example, https://gorest.co.in/public/v1/users/9, where 9 is the user id.

Calling POST API

HTTP POST call is generally made when you want to create new records using REST API. You might need to send also authorization token in the header and here I am going to show you how to do that.

Let’s take the following code example:

// Url for making POST request
URL postUrl = new URL("https://gorest.co.in/public/v1/users");

String token = "eyJraWQioiJRVWRuYlktQmpaODFCaDRZMENfOVlyUVJpa3IyYkZDLVFQNXJtS0taUk9nIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkxGb3hscnJ1cUdIdHl0QjUzOFMzUGdwMng5QlI3djNMN3J5Qm5FLThGM00iLCJpc3MiOiJodHRwczovL2RpZGVudGl0eWRldi5va3RhcHJldmlldy5jb20iLCJhdWQiOiJodHRwczovL2RpZGVudGl0eWRldi5va3RhcHJldmlldy5jb20iLCJzdWIiOiJzc2Fya2E4QHByb2RkZnMucGYuZGlzY292ZXJmaW5hbmNpYWwuY29tIwiaWF0IjoxNjM4NDYyNTQ0LCJleHAiOjE2Mzg0NjYxNDQsImNpZCI6IjBvYTEzZnBudHp2b3VVQlNwMGg4IiwidWlkIjoiMDB1MTFkNGd4Njh6S0dzOVgwaDgiLCJzY3AiOlsib3BlbmlkIiwiZW1haWwiLCJwcm9maWxlIl19.X3WNN0iji7aq7eiba6p3EKYSbQoIMpG5p1e8Wmh_oZtqu2x2GfumyCIcOp9i-A-LidrELrnrz0uhbePFni4ONY7rUvB7ALDGOPINh0ksiOwSuMEOkhFSWTfOGW1tak3At8KgEqNmysoOJ5O8MESZMEyGf0qlrEwqqO8aYpcdR47j1DJQ7ijteVTISZr89uzlaLknIZabhisncRMx9kKCGiRD-eaLr0gvREQ93tch3Tq8dXH9fsx0Ea9n4NlnMTmOrKNHZVk2yODIM9Qw4CplfFAe9s_NCdwMj3aF-yTd_mC502HJMN0vI4VUT9BpF9si2DA26K1pWhxe-B2nKxFZ-w";

HttpsURLConnection connection = (HttpsURLConnection) postUrl.openConnection();

// Set POST as request method
connection.setRequestMethod("POST");

// Setting Header Parameters
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.setUseCaches(false);
connection.setDoOutput(true);

// Adding Body payload for POST request
String params = "{\"name\":\"Soumitra Roy\", \"gender\":\"male\", \"email\":[mailto:soumitra@roytuts.com]soumitra@roytuts.com\", \"status\":\"active\"}";

BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
wr.write(params);
wr.close();

connection.connect();

// Getting Response
int statusCode = connection.getResponseCode();

// Checking http status code for 201 (Created)
if (statusCode == HttpsURLConnection.HTTP_CREATED) {
	StringBuffer jsonResponseData = new StringBuffer();
	String readLine = null;
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

	while ((readLine = bufferedReader.readLine()) != null) {
		jsonResponseData.append(readLine + "\n");
	}

	bufferedReader.close();
	System.out.println(jsonResponseData.toString());

} else {
	System.out.println(statusCode);
}

Here also I have created URL and HttpsUrlConnection objects and set the HTTP method POST in the request.

Setting some properties in the http header:

connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.setUseCaches(false);
connection.setDoOutput(true);

Setting Content-Type, Authorization in the header. I do not want to cache and also I want the output from the URL connection.

I am sending the payload in the body of the request, so using BufferedWriter:

String params = "{\"name\":\"Soumitra Roy\", \"gender\":\"male\", \"email\":[mailto:soumitra@roytuts.com]soumitra@roytuts.com\", \"status\":\"active\"}";

BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
wr.write(params);
wr.close();

Here also I am checking for a particular status code (201 is for creation a new resource in the server) and getting the response data from URL connection stream and finally log in the console.

Proxy Server in the URL Connection

If you need to use proxy server connection in the REST API URL, then you can use the proxy connection object in the following manner.

URL postUrl = new URL("https://dev.oktapreview.com/oauth2/v1/userinfo");

Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("proxy-cloud.example.com", 8080));

So, first create a Proxy object and pass the Proxy object in the HttpsUrlConnection’s openConnection() method. And this proxy object can be passed for your any HTTP request, GET, POST, etc.

You should pass the proxy object in the connection object:

HttpsURLConnection connection = (HttpsURLConnection) postUrl.openConnection(proxy);

Hope you understood how to call GET/POST REST APIs suing proxy and http headers.

Source Code

Download

Leave a Reply

Your email address will not be published.