本文介绍使用 Java 代码访问第三方接口,并携带 Token 和设置请求头(Authorization 和 Content-Type)的示例。详细解释了如何使用 HttpURLConnection 类发送 GET 请求,并处理响应结果。

下面是一个使用 Java 代码访问第三方接口并携带 token 和设置请求头的示例:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class APIRequestExample {

    public static void main(String[] args) throws Exception {
        // 设置请求URL
        String apiUrl = "https://example.com/api/endpoint";

        // 设置token
        String token = "<your token>";

        // 创建URL对象
        URL url = new URL(apiUrl);

        // 创建HttpURLConnection对象
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为GET
        connection.setRequestMethod("GET");

        // 设置请求头
        connection.setRequestProperty("Authorization", token);
        connection.setRequestProperty("Content-Type", "application/json");

        // 发送请求并获取响应
        int responseCode = connection.getResponseCode();

        // 读取响应内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 打印响应结果
        System.out.println("Response Code: " + responseCode);
        System.out.println("Response Body: " + response.toString());

        // 关闭连接
        connection.disconnect();
    }
}

在上面的示例中,我们首先设置了请求URL和token。然后创建了URL对象,并使用该URL对象创建了HttpURLConnection对象。

接下来,我们设置请求方法为GET,并设置请求头的Authorization为token,Content-Type为application/json。

然后,我们发送请求并获取响应。在获取响应后,我们使用BufferedReader逐行读取响应内容,并将其存储在StringBuilder中。

最后,我们打印响应结果,并关闭连接。

请注意,上述示例仅适用于GET请求。如果需要进行其他类型的请求,可以使用相应的方法(如POST、PUT、DELETE等),并根据需要设置请求体内容。


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

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