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

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...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...