Implementing GET and POST Request for calling third party API in Java
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.
- GET
- POST
- HEAD
- OPTIONS
- PUT
- DELETE
- 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 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 :
- Spring Boot CRUD operations using Rest API, JPA and MySql
- Spring Boot Crud Operation with Thymeleaf + MySql + JPA
Comments
Post a Comment