import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class ThirdPartyAPIExample {
// 发起HTTP POST请求调用第三方接口
public static String callThirdPartyAPI(String apiUrl, String jsonPayload) {
try {
// 创建URL对象
URL url = new URL(apiUrl);
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头,指定内容类型为JSON
conn.setRequestProperty("Content-Type", "application/json; utf-8");
// 允许发送请求体
conn.setDoOutput(true);
// 将JSON字符串写入请求体
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
StringBuilder response = new StringBuilder();
String currentLine;
while ((currentLine = in.readLine()) != null) {
response.append(currentLine);
}
// 返回响应内容
return response.toString();
}
} else {
// 如果不是200响应,返回错误信息
return "Error: HTTP error code : " + responseCode;
}
} catch (Exception e) {
// 捕获异常并返回错误信息
return "Error: " + e.getMessage();
}
}
public static void main(String[] args) {
// 示例API URL
String apiUrl = "https://api.example.com/data";
// 示例JSON Payload
String jsonPayload = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
// 调用第三方API并打印结果
String result = callThirdPartyAPI(apiUrl, jsonPayload);
System.out.println(result);
}
}
new URL(apiUrl)
创建一个URL对象。url.openConnection()
打开到该URL的连接,并将其转换为HttpURLConnection
。conn.setRequestMethod("POST")
设置请求方法为POST,并通过conn.setRequestProperty
设置请求头。OutputStream
将JSON格式的请求体写入HTTP请求中。这个示例展示了如何通过Java代码发起一个HTTP POST请求来调用第三方API。
上一篇:java递归查询所有子节点
下一篇:java值传递和引用传递
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站