// 导入必要的库
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 {
// 定义调用第三方接口的方法
public static String callThirdPartyAPI(String urlStr, String jsonPayload) {
try {
// 创建URL对象
URL url = new URL(urlStr);
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
conn.setRequestMethod("POST");
// 设置请求头,表明发送的数据格式为JSON
conn.setRequestProperty("Content-Type", "application/json; utf-8");
// 允许向连接输出数据
conn.setDoOutput(true);
// 发送请求体
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) { // 成功
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
// 关闭流
in.close();
// 返回响应内容
return content.toString();
} else {
// 如果响应码不是200,返回错误信息
return "Error: " + responseCode;
}
} catch (Exception e) {
// 捕获异常并返回错误信息
return "Error: " + e.getMessage();
}
}
// 测试方法
public static void main(String[] args) {
// 示例URL和JSON负载
String url = "https://api.example.com/endpoint";
String jsonPayload = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
// 调用第三方接口并打印结果
System.out.println(callThirdPartyAPI(url, jsonPayload));
}
}
URL
对象。HttpURLConnection
类打开与目标服务器的连接。POST
,并设置请求头以指定发送的数据格式为JSON。OutputStream
将JSON格式的请求体发送到服务器。main
方法中提供了一个示例URL和JSON负载,并调用callThirdPartyAPI
方法来测试接口调用。希望这段代码和解释对你有帮助!
上一篇:java随机生成字符串
下一篇:java 8 lambda
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站