如何使用Java进行HTTP请求并处理响应错误

原创 青旅半醒 2024-11-26 07:18 188阅读 0赞

在Java中,我们可以使用HttpURLConnection或者HttpClient来发送HTTP请求。下面是一个使用HttpURLConnection的例子:

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. public class Main {
  6. public static void main(String[] args) {
  7. // 创建URL对象
  8. URL url = new URL("http://example.com");
  9. // 创建连接
  10. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  11. // 设置请求方法(GET或POST等)
  12. connection.setRequestMethod("GET");
  13. // 获取响应状态码
  14. int responseCode = connection.getResponseCode();
  15. System.out.println("Response Code: " + responseCode);
  16. // 处理响应数据
  17. if (responseCode == 200) {
  18. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
  19. String inputLine;
  20. StringBuffer content = new StringBuffer();
  21. while ((inputLine = in.readLine()) != null)) {
  22. content.append(inputLine);
  23. }
  24. in.close();
  25. System.out.println("Response Content: " + content.toString());
  26. } else {
  27. System.out.println("Failed to retrieve data. Response Code: " + responseCode);
  28. }
  29. }
  30. }

这个例子中,我们发送了一个GET请求到指定的URL。然后处理了响应的状态码,并根据状态码来决定是否打印响应内容以及如何处理错误。

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

发表评论

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

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

相关阅读