使用Java实现HTTP客户端的基本请求

原创 心已赠人 2024-12-01 16:48 147阅读 0赞

在Java中,我们可以使用HttpURLConnection或Apache 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 SimpleHttpClient {
  6. public static void main(String[] args) {
  7. // 创建URL对象
  8. URL url = new URL("http://example.com");
  9. // 发送GET请求
  10. try (HttpURLConnection connection = (HttpURLConnection) url.openConnection()) {
  11. // 设置连接为非KeepAlive模式
  12. connection.setRequestProperty("Connection", "close");
  13. // 执行GET请求
  14. int responseCode = connection.getResponseCode();
  15. System.out.println("Response Code: " + responseCode);
  16. // 读取响应数据
  17. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
  18. String inputLine;
  19. StringBuffer content = new StringBuffer();
  20. while ((inputLine = in.readLine()) != null)) {
  21. content.append(inputLine);
  22. }
  23. in.close();
  24. System.out.println("Response Content: " + content.toString());
  25. } catch (Exception e) {
  26. System.err.println(e.getMessage());
  27. e.printStackTrace();
  28. }
  29. }
  30. }

这段代码创建了一个HTTP GET请求到http://example.com。如果服务器响应,内容将被打印出来。同时,它还处理了可能的异常情况。

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

发表评论

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

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

相关阅读