Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing HTTP Clients for Third-Party API Integration in Java

Tech May 13 1

To demonstrate the various methods of consuming external REST APIs in Java, we will use a standard entity and a mock controller as the target endpoints.

1. Mock API Environment Setup

Define a POJO representing the data structure.

public class Account {
    private String id;
    private String username;
    private String password;
    private String gender;

    // Standard Getters, Setters, and toString implementation omitted for brevity
}

The following Spring Boot controller simulates the third-party service provider. It runs on port 8089.

@RestController
@RequestMapping("/api/users")
public class MockServiceProvider {

    @GetMapping("/fetch")
    public String fetchData() {
        return "GET request processed successfully";
    }

    @PostMapping("/create")
    public String createRecord(@RequestBody Account account) {
        return "POST request processed: " + account.toString();
    }
}

2. Approach 1: Native JDK HttpURLConnection

This method relies on the standard Java Development Kit (JDK) without requiring external dependencies. It involves manual management of input and output streams.

Implementation

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class JdkHttpClient {

    public static String executePost(String targetUrl, String jsonPayload) {
        HttpURLConnection connection = null;
        StringBuilder response = new StringBuilder();

        try {
            URL url = new URL(targetUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "*/*");

            try (OutputStream os = connection.getOutputStream();
                 OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
                writer.write(jsonPayload);
                writer.flush();
            }

            try (InputStream is = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response.toString();
    }

    public static String executeGet(String targetUrl) {
        StringBuilder response = new StringBuilder();
        HttpURLConnection connection = null;

        try {
            URL url = new URL(targetUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setRequestProperty("Accept", "application/json");

            try (InputStream is = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return response.toString();
    }
}

Test Execution

public class JdkClientTest {
    public static void main(String[] args) {
        String baseUrl = "http://localhost:8089/api/users";

        String getResult = JdkHttpClient.executeGet(baseUrl + "/fetch");
        System.out.println("JDK GET Response: " + getResult);

        Account acc = new Account();
        acc.setId("101");
        acc.setUsername("john_doe");
        acc.setPassword("secret");
        acc.setGender("Male");

        String jsonPayload = JSON.toJSONString(acc); // Using Fastjson or similar
        String postResult = JdkHttpClient.executePost(baseUrl + "/create", jsonPayload);
        System.out.println("JDK POST Response: " + postResult);
    }
}

3. Approach 2: Apache Commons HttpClient

The Apache Commons HttpClient library simplifies HTTP interactions by abstracting the low-level connection details.

Maven Dependency

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

Implementation

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class ApacheCommonsClient {

    public static String sendGet(String url) {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        
        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        
        String responseBody = "";
        try {
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + method.getStatusLine());
            }
            responseBody = method.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return responseBody;
    }

    public static String sendPost(String url, String jsonBody) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        
        method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        method.setRequestHeader("Accept", "*/*");
        
        try {
            StringRequestEntity entity = new StringRequestEntity(jsonBody, "application/json", "UTF-8");
            method.setRequestEntity(entity);
            
            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                return method.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return "Error";
    }
}

4. Approach 3: Hutool HttpUtil

Hutool is a comprehensive Java utility library that offers a highly simplified API for HTTP requests, handling connection management and encoding automatically.

Maven Dependency

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.1</version>
</dependency>

Usage Examples

import cn.hutool.http.HttpUtil;
import cn.hutool.core.util.CharsetUtil;
import java.util.HashMap;
import java.util.Map;

public class HutoolClientDemo {
    public static void main(String[] args) {
        // Simple GET request
        String content = HttpUtil.get("http://localhost:8089/api/users/fetch");
        System.out.println("Hutool GET: " + content);

        // GET with parameters (automatically encoded and appended to URL)
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("userId", "100");
        String paramResult = HttpUtil.get("http://example.com/search", queryParams);

        // POST request with form data
        Map<String, Object> formParams = new HashMap<>();
        formParams.put("username", "admin");
        formParams.put("password", "123456");
        String postResult = HttpUtil.post("http://localhost:8089/api/users/create", formParams);
        System.out.println("Hutool POST: " + postResult);
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.