Java调用第三方接口的秘籍:技巧、案例与最佳实践
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ThirdPartyApiCaller {
public static void main(String[] args) {
String apiUrl = "http://api.example.com/data";
String apiKey = "your_api_key_here";
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
System.out.println("Response: " + response.toString());
} else {
System.out.println("GET request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码展示了如何使用Java发起一个简单的HTTP GET请求到第三方API,并处理返回的响应。它使用了HttpURLConnection
类,这是Java标准库中处理HTTP请求的一个基本方式。代码中包含了设置请求头(例如认证方式),以及处理响应的基本逻辑。
评论已关闭