以下是一个使用Java代码从API端点接收API响应的示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://api.example.com/endpoint");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
conn.setRequestMethod("GET");
// 获取API响应的状态码
int responseCode = conn.getResponseCode();
// 根据状态码判断请求是否成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取API响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印API响应内容
System.out.println(response.toString());
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
// 关闭连接
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码使用java.net.URL
和java.net.HttpURLConnection
类来发送GET请求到API端点,并从API响应中读取内容。请替换https://api.example.com/endpoint
为实际的API端点URL。