使用Java进行网络编程,HTTP请求与响应示例

原创 r囧r小猫 2024-12-01 04:48 179阅读 0赞

在Java中,我们可以使用java.net和java.io包来实现HTTP请求与响应。以下是一个简单的示例,使用HttpURLConnection进行GET请求:

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. public class HttpGetExample {
  6. public static void main(String[] args) {
  7. String urlStr = "http://example.com/api/data"; // Replace with your API endpoint
  8. try {
  9. URL url = new URL(urlStr);
  10. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  11. // Set request method
  12. connection.setRequestMethod("GET");
  13. // Check if response code is 200 (OK)
  14. int responseCode = connection.getResponseCode();
  15. System.out.println("Response Code: " + responseCode);
  16. // If the request was successful, read the response
  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. }
  28. }
  29. }

注意:这个示例使用的是HttpURLConnection,这是Java中处理HTTP请求和响应的传统方式。如果需要更高级的API,如java.net.HttpClient,可能会更适合现代的网络编程需求。

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

发表评论

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

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

相关阅读