Java 调用第三方接口传递 JSON 数据 - HttpURLConnection 和 RestTemplate 示例

本文将介绍如何使用 Java 调用第三方接口并传递 JSON 数据。我们将展示使用两种常见的库:HttpURLConnection 和 RestTemplate,并提供示例代码。

使用 HttpURLConnection 类

HttpURLConnection 是 Java 中内置的类,用于处理 HTTP 请求。以下示例代码演示了如何使用 HttpURLConnection 类发送 POST 请求并传递 JSON 数据:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;

public class ApiCall {
    public static void main(String[] args) throws Exception {
        String url = "http://example.com/api";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法和请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        // 构造 JSON 请求体
        String jsonBody = '{"key1":"value1","key2":"value2"}';

        // 发送请求
        con.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(jsonBody);
        wr.flush();
        wr.close();

        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 打印响应结果
        System.out.println(response.toString());
    }
}

该示例代码使用 POST 方法向 http://example.com/api 发送一个 JSON 请求体,响应体将被读取并打印到控制台上。要修改为自己的接口和 JSON 请求体,只需要修改 url 和 jsonBody 变量的值即可。

使用 RestTemplate 类

RestTemplate 是 Spring Framework 提供的类,用于发送 HTTP 请求和接收响应。如果您在项目中已经使用了 Spring Framework,可以使用 RestTemplate 类简化代码。以下示例代码演示了如何使用 RestTemplate 类发送 POST 请求并传递 JSON 数据:

import org.springframework.web.client.RestTemplate;

public class ApiCall {
    public static void main(String[] args) {
        String url = "http://example.com/api";
        String jsonBody = '{"key1":"value1","key2":"value2"}';

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject(url, jsonBody, String.class);

        System.out.println(response);
    }
}

该示例代码与上一个示例代码的功能相同,但使用了 RestTemplate 类来发送请求和接收响应。要修改为自己的接口和 JSON 请求体,只需要修改 url 和 jsonBody 变量的值即可。

总结

本文展示了两种方法使用 Java 调用第三方接口并传递 JSON 数据。您可以选择最适合您的项目需求的方法。HttpURLConnection 是 Java 内置的类,而 RestTemplate 是 Spring Framework 提供的类,可以简化代码。无论您选择哪种方法,都需要确保修改代码以适应您的特定接口和 JSON 请求体。

Java 调用第三方接口传递 JSON 数据 -  HttpURLConnection 和 RestTemplate 示例

原文地址: https://www.cveoy.top/t/topic/oLlJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录