java访问第三方接口需要请求头携带token并且提交类型 Content-Type :applicationjson 代码
以下是一个使用Java访问第三方接口并携带token和设置Content-Type为application/json的示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ThirdPartyApiAccess {
public static void main(String[] args) {
try {
String url = "https://api.example.com/endpoint";
String token = "your_token_here";
String jsonPayload = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
// 设置请求头
connection.setRequestProperty("Authorization", "Bearer " + token);
connection.setRequestProperty("Content-Type", "application/json");
// 设置请求方法为POST
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 发送请求体数据
connection.getOutputStream().write(jsonPayload.getBytes());
// 获取响应结果
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();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例代码中,我们首先指定了访问的URL、token和要提交的JSON数据。然后,我们创建一个URL对象,并使用它打开一个HttpURLConnection连接。接下来,我们设置请求头的Authorization字段为"Bearer "加上token,设置Content-Type为application/json。然后,我们设置请求方法为POST,并设置请求体数据为jsonPayload。最后,我们获取响应的状态码和响应体数据并输出到控制台。
请注意,以上代码仅供参考,实际情况可能因第三方接口的要求而有所不同。您可能需要根据接口文档和要求进行适当的修改
原文地址: http://www.cveoy.top/t/topic/irjZ 著作权归作者所有。请勿转载和采集!