Skip to main content

How to call 3rd party API in Java using HttpURLConnection | Get and Post Request

Implementing GET and POST Request for calling third party API in Java

Java code for calling 3rd party rest api 

As a developer, often times we need to call third party APIs for getting or saving data. We can simply call GET request for getting data and POST request for save data or if needed to send parameters in body section. 

In this article, we seen how we can use GET and POST request for calling third party Rest APIs.

In java, we can simply call third party API using HttpURLConnection class and get response accordingly. 

We can use following methods in HttpURLConnection class.

  1. GET
  2. POST
  3. HEAD
  4. OPTIONS
  5. PUT
  6. DELETE
  7. TRACE

So lets see how we can call third party API. i am using https://jsonplaceholder.typicode.com  to make GET and POST calls. This website provides free API endpoints.

Get and post request for calling 3rd party API

GET request :

Get request simply returns data (response). GET request does not accepts any body section data. See sample of GET requests :

  • https://example.com/data 
  • https://example.com/data/1

Calling GET request is easy. Because simply we have to pass parameters only.

So lets first see how we can use GET for getting response.

Example 1 : Java Code for calling 3rd party GET request

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetAPI {

    public static void main(String[] args) {
       
        try {
            getApiRequest();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    
    public static void getApiRequest() throws IOException {
       
        // Get 10th record data
        URL getUrl = new URL("https://jsonplaceholder.typicode.com/posts/10");
       
        HttpURLConnection conection = (HttpURLConnection) getUrl.openConnection();
       
        // Set request method
        conection.setRequestMethod("GET");

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

        // If responseCode is 200 means we get data successfully
        if (responseCode == HttpURLConnection.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("JSON String Data " + jsonResponseData.toString());
        } else {
            System.out.println(responseCode);
        }

    }

}

Output :

JSON String Response : {  
    "userId": 1, 
    "id": 10, 
    "title": "optio molestias id quia eum", 
    "body": "quo et expedita modi cum officia vel magni\
        ndoloribus qui repudiandae\nvero nisi sit\
        nquos veniam quod sed accusamus veritatis error
"
}

In above API request, we are request for 10th id response. You can also call "https://jsonplaceholder.typicode.com/posts/" API. It will return 100 records.

POST request :

In POST request, we have to pass data in body section. like if we want to save data then we can use POST request. so lets see how we can implement in java code.

Example 2 : Java Code for calling third party POST request

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostAPI {

    public static void main(String[] args) {
        try {
            postApiRequest();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void postApiRequest() throws IOException {
       
        // Url for making POST request
        URL postUrl = new URL("https://jsonplaceholder.typicode.com/posts");

        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
       
        // Set POST as request method
        connection.setRequestMethod("POST");
       
        // Setting Header Parameters
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
       
        // Adding Body section of POST request
        String params="title=foo&body=bar&userId=1";

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

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

// Checking ckode for 201 (Created)
        if (responseCode == HttpURLConnection.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(responseCode);
}

    }

}

Output :

{
  "title": "foo",
  "body": "bar",
  "userId": "1",
  "id": 101
}

If we get responseCode 201, means data is successfully created. 

If we want to pass any header we can use setRequestProperty() method of HttpURLConnection class.

If we want to pass body in POST request, we must to set connection.setDoOutput(true) otherwise it will give following error :

  • java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)

If any third party API requires token for Authorization we can set in setRequestProperty() method like following.

connection.setRequestProperty("Authorization", "Bearer "+ accessToken);


Happy Coding.

Spring boot crud operation with Rest API :




Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last