使用Java编写HTTP客户端请求示例

原创 悠悠 2024-12-06 16:51 137阅读 0赞

在Java中,我们可以使用Apache HttpClient或者java.net.URLConnection来发送HTTP请求。以下是一个使用HttpClient的简单示例:

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.client.methods.CloseableHttpResponse;
  3. import org.apache.http.client.methods.HttpGet;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.json.JSONObject;
  7. public class HttpClientRequest {
  8. public static void main(String[] args) {
  9. // 创建HttpClient
  10. CloseableHttpClient httpClient = HttpClients.createDefault();
  11. try {
  12. // 发送GET请求
  13. HttpGet httpGet = new HttpGet("http://example.com"); // 替换为你要访问的URL
  14. // 获取响应
  15. CloseableHttpResponse response = httpClient.execute(httpGet);
  16. if (response.getStatusLine().getStatusCode() == 200) { // 如果状态码是200(表示成功),
  17. HttpEntity entity = response.getEntity(); // 获取实体内容
  18. if (entity != null && entity.getContentLength() > 0) { // 如果实体内容非空
  19. String jsonString = EntityUtils.toString(entity, "UTF-8")); // 将实体内容转换为字符串
  20. JSONObject jsonObject = new JSONObject(jsonString); // 将字符串解析为JSONObject
  21. System.out.println(jsonObject); // 打印解析后的JSON对象
  22. }
  23. } else { // 如果状态码不是200
  24. System.out.println("Failed to fetch data. Status code: " + response.getStatusLine().getStatusCode());
  25. }
  26. // 关闭资源
  27. response.close();
  28. httpClient.close();
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

这个示例中,我们创建了一个HttpClient实例,然后使用HttpGet发送一个GET请求到指定的URL。如果返回的状态码是200,我们就打印出响应的数据。

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

发表评论

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

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

相关阅读