Java HTTP客户端:GET/POST请求示例

原创 傷城~ 2024-12-01 05:15 76阅读 0赞

在Java中,我们可以使用HttpURLConnection或者HttpClient来发送HTTP GET或POST请求。这里我将提供这两种方法的示例。

  1. 使用HttpURLConnection:
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. public class HttpClientGETExample {
  6. public static void main(String[] args) {
  7. // 创建URL对象
  8. URL url = new URL("http://example.com");
  9. // 创建HttpURLConnection对象
  10. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  11. // 设置请求方法(GET或POST)
  12. connection.setRequestMethod("GET");
  13. // 如果是POST请求,需要设置请求体
  14. // connection.setDoOutput(true);
  15. // String postBody = "Your POST body";
  16. // byte[] postBytes = postBody.getBytes();
  17. // connection.getOutputStream().write(postBytes);
  18. // 获取响应状态码
  19. int responseCode = connection.getResponseCode();
  20. // 打印响应状态码
  21. System.out.println("Response Code: " + responseCode);
  22. // 读取并打印响应内容(如果是POST请求,需要处理请求体)
  23. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
  24. String outputLine;
  25. while ((outputLine = reader.readLine()) != null)) {
  26. System.out.println(outputLine);
  27. }
  28. }
  29. }
  1. 使用HttpClient:

如果你使用的是Apache HttpClient,那么示例会稍微有所不同。这里我提供一个基本的GET请求示例:

  1. import org.apache.http.HttpResponse;
  2. import org.apache.http.client.methods.HttpGet;
  3. import org.apache.http.impl.client.CloseableHttpClient;
  4. import org.apache.http.impl.client.HttpClients;
  5. import org.apache.http.util.EntityUtils;
  6. public class HttpClientGETExample {
  7. public static void main(String[] args) throws Exception {
  8. // 创建HttpClient对象
  9. CloseableHttpClient httpClient = HttpClients.createDefault();
  10. // 创建HttpGet请求对象
  11. HttpGet httpGet = new HttpGet("http://example.com");
  12. try (HttpResponse response = httpClient.execute(httpGet)) {
  13. // 获取响应状态码
  14. int statusCode = response.getStatusLine().getStatusCode();
  15. System.out.println("Response Status Code: " + statusCode);
  16. // 如果状态码为200(OK),则读取并打印响应内容
  17. if (statusCode == 200) {
  18. String responseContent = EntityUtils.toString(response.getEntity(), "UTF-8"));
  19. System.out.println("Response Content: " + responseContent);
  20. }
  21. } catch (Exception e) {
  22. System.err.println(e.getMessage());
  23. e.printStackTrace();
  24. }
  25. }
  26. }

以上示例展示了如何使用Java的HttpURLConnection或者HttpClient发送GET请求。

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

发表评论

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

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

相关阅读