如何使用Java进行网络编程,如HTTP请求?

原创 水深无声 2025-03-17 11:12 13阅读 0赞

在Java中,我们可以使用Java的内置库如java.net.URLjavax.xml.parsers.DocumentBuilderFactory等来进行HTTP请求。

以下是一个简单的例子,使用HttpURLConnection发送一个GET请求到一个URL:

  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. String urlStr = "http://example.com"; // 你的URL
  8. URL url = new URL(urlStr);
  9. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  10. conn.setRequestMethod("GET"); // 发送GET请求
  11. int responseCode = conn.getResponseCode(); // 获取响应码
  12. System.out.println("Response Code: " + responseCode);
  13. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))); // 读取响应内容
  14. String inputLine;
  15. StringBuffer content = new StringBuffer();
  16. while ((inputLine = in.readLine()) != null) {
  17. content.append(inputLine);
  18. }
  19. in.close();
  20. System.out.println("Response Content: " + content.toString());
  21. }
  22. }

这段代码会发送一个GET请求到指定的URL,然后打印出响应码和内容。请根据你的实际需求进行修改。

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

发表评论

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

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

相关阅读