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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...