java访问第三方接口需要请求头携带token Authorization your token并且提交类型 Content-Type :applicationjson 为post请求代码
下面是一个Java中使用POST请求访问第三方接口并携带请求头的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class APIRequest {
public static void main(String[] args) {
String url = "https://api.example.com/endpoint";
String token = "<your token>";
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
try {
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", token);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response;
StringBuilder responseContent = new StringBuilder();
while ((response = reader.readLine()) != null) {
responseContent.append(response);
}
reader.close();
System.out.println(responseContent.toString());
} else {
System.out.println("Request failed with response code: " + responseCode);
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请注意替换url和token的值以及根据需要修改requestBody的内容。这个示例代码使用HttpURLConnection进行HTTP请求,并且设置了Authorization和Content-Type请求头,并以JSON格式发送POST请求。最后,它打印出了API的响应结果
原文地址: http://www.cveoy.top/t/topic/irj5 著作权归作者所有。请勿转载和采集!