Ultimate Guide to the REST API Calls using Java Mapping
Introduction
When working with SAP PI/PO or SAP CPI, Java Mapping plays a crucial role in transforming and integrating data. Often, developers need to make REST API calls within Java Mapping to fetch or send data dynamically. This blog post explores two approaches: using HttpURLConnection
and OkHttp
for both GET and POST requests.
1. Using HttpURLConnection for REST API Calls
HttpURLConnection
is a built-in Java class that provides a simple way to make HTTP requests. Here’s how to perform GET and POST operations using HttpURLConnection
.
Required Imports for HttpURLConnection
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
GET Request with HttpURLConnection
public class RestClient {
public static void main(String[] args) {
try {
String apiUrl = "https://jsonplaceholder.typicode.com/posts/1";
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
POST Request with HttpURLConnection
public class PostRequest {
public static void main(String[] args) {
try {
String apiUrl = "https://jsonplaceholder.typicode.com/posts";
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
String jsonInput = "{\"title\":\"foo\", \"body\":\"bar\", \"userId\":1}";
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInput.getBytes("utf-8");
os.write(input, 0, input.length);
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response;
while ((response = br.readLine()) != null) {
System.out.println(response);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Using OkHttp for REST API Calls
OkHttp
is a third-party HTTP client for Java that provides a more modern and efficient way to handle HTTP requests.
Required Imports for OkHttp
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
Adding OkHttp Dependency
If you’re using Maven, add the following dependency:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
GET Request with OkHttp
public class OkHttpGetExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts/1")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
POST Request with OkHttp
public class OkHttpPostExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
String json = "{\"title\":\"foo\", \"body\":\"bar\", \"userId\":1}";
RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url("https://jsonplaceholder.typicode.com/posts")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Comparison: HttpURLConnection vs OkHttp
Feature | HttpURLConnection | OkHttp |
---|---|---|
Built-in Support | Yes (Java SE) | No (Requires dependency) |
Simplicity | Moderate | Easy |
Performance | Average | High |
Connection Reuse | Limited | Efficient |
Asynchronous Support | No | Yes (via callbacks) |
Customization | Limited | Extensive |
Conclusion
Both HttpURLConnection
and OkHttp
can be used for making REST API calls in Java Mapping. While HttpURLConnection
is built-in and lightweight, OkHttp
provides a more modern and flexible approach. Depending on the project requirements, either can be utilized effectively.
Key Takeaways:
HttpURLConnection
is part of the Java standard library and requires no additional dependencies.OkHttp
is more powerful, efficient, and widely used for production applications.OkHttp
supports asynchronous calls, making it preferable for non-blocking operations.- Both methods can be integrated into SAP PI/PO or CPI Java Mapping scenarios.
By implementing these approaches, developers can efficiently make REST API calls in their integration projects. If you have any questions or suggestions, feel free to comment below!
External Libraries Required
okhttp: download here
okio: download here
Post Comment