API调用错误示例:Java如何正确使用HTTP客户端

原创 àì夳堔傛蜴生んèń 2024-10-14 06:51 127阅读 0赞

在Java中,我们可以使用各种HTTP客户端库来发送API请求。这里以java.net.HttpURLConnection和流行的Apache HttpClient库为例。

  1. 使用HttpURLConnection:
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. public class HttpURLConnectionExample {
  6. public static void main(String[] args) throws Exception {
  7. // 创建URL对象
  8. URL url = new URL("https://api.example.com/endpoint");
  9. // 使用HttpURLConnection发送GET请求
  10. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  11. connection.setRequestMethod("GET");
  12. connection.setConnectTimeout(1000); // 设置连接超时
  13. int responseCode = connection.getResponseCode();
  14. if (responseCode == 200) { // 如果响应码为200(成功),则读取响应内容
  15. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())));
  16. String inputLine;
  17. StringBuffer content = new StringBuffer();
  18. while ((inputLine = in.readLine()) != null) {
  19. content.append(inputLine);
  20. }
  21. System.out.println("API Response Content: " + content.toString());
  22. } else {
  23. System.out.println("Failed to retrieve API data. Response Code: " + responseCode);
  24. }
  25. connection.disconnect();
  26. }
  27. }
  1. 使用Apache HttpClient库:
  1. import org.apache.http.HttpResponse;
  2. import org.apache.http.client.methods.HttpGet;
  3. import org.apache.http.impl.client.CloseableHttpClient;
  4. import org.apache.http.util.EntityUtils;
  5. public class ApacheHttpClientExample {
  6. public static void main(String[] args) throws Exception {
  7. // 创建CloseableHttpClient对象
  8. CloseableHttpClient httpClient = HttpClients.createDefault();
  9. // 使用Apache HttpClient发送GET请求
  10. HttpGet httpGet = new HttpGet("https://api.example.com/endpoint");
  11. HttpResponse response = httpClient.execute(httpGet);
  12. int responseCode = response.getStatusLine().getStatusCode();
  13. if (responseCode == 200) {
  14. String content = EntityUtils.toString(response.getEntity()));
  15. System.out.println("API Response Content: " + content);
  16. } else {
  17. System.out.println("Failed to retrieve API data. Response Code: " + responseCode));
  18. }
  19. // 关闭HttpClient连接
  20. httpClient.close();
  21. }
  22. }

请确保你已经添加了相应的依赖项。例如,如果你使用的是Apache HttpClient,你需要在项目的pom.xml文件中添加对应的依赖。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,127人围观)

还没有评论,来说两句吧...

相关阅读