如何通过Java实现网络通信——HTTP请求

原创 不念不忘少年蓝@ 2024-12-10 12:51 136阅读 0赞

在Java中,我们可以使用HttpURLConnection或者更高级的如OkHttp、RestTemplate等库来实现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 HttpClientExample {
  6. public static void main(String[] args) {
  7. // 创建URL对象
  8. URL url = new URL("http://example.com/api/data");
  9. try (HttpURLConnection connection = (HttpURLConnection) url.openConnection()) {
  10. // 设置请求方法
  11. connection.setRequestMethod("GET");
  12. // 检查响应码
  13. int responseCode = connection.getResponseCode();
  14. if (responseCode == 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(content.toString());
  22. }
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }

这个例子中,我们创建了一个到”example.com/api/data”的GET请求。如果返回的状态码是200(表示成功),我们就读取响应数据并打印出来。

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

发表评论

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

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

相关阅读