用 Java 发送 HTTP 请求

Sheeraz Gul 2024年2月15日
  1. 在 Java 中使用 HttpURLConnection 发送 HTTP 请求
  2. 在 Java 中使用 Apache HttpClient 来发送 HTTP 请求
用 Java 发送 HTTP 请求

我们可以使用 Java HttpURLConnection 和 Apache HttpClient 在 Java 中发送 HTTP 请求。本教程将演示如何使用 Java 中的两种方法发送 HTTP 请求。

在 Java 中使用 HttpURLConnection 发送 HTTP 请求

HttpURLConnection 是来自 Java.net 库的内置方法。HTTP 请求有两种类型,GET 和 POST。

让我们尝试使用 HttpURLConnection 发送两者。

在 Java 中使用 HttpURLConnection 发送 GET HTTP 请求

让我们尝试使用 GET 方法 HttpURLConnection 方法来获取我们网页的内容。

例子:

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Get_HttpURLConnection {
  private static HttpURLConnection get_connection;

  public static void main(String[] args) throws IOException {
    String url = "https://www.delftstack.com/";

    try {
      // We retrieve the contents of our webpage.
      URL myurl = new URL(url);
      get_connection = (HttpURLConnection) myurl.openConnection();
      // Here we specify the connection type
      get_connection.setRequestMethod("GET");
      StringBuilder webpage_content;

      try (BufferedReader webpage =
               new BufferedReader(new InputStreamReader(get_connection.getInputStream()))) {
        String webpage_line;
        webpage_content = new StringBuilder();

        while ((webpage_line = webpage.readLine()) != null) {
          webpage_content.append(webpage_line);
          webpage_content.append(System.lineSeparator());
        }
      }

      System.out.println(webpage_content.toString());

    } finally {
      // Disconnect the connection
      get_connection.disconnect();
    }
  }
}

上面的代码会从 https://www.delftstack.com/ 输出大量内容。

输出:

获取 HttpURL 连接

在 Java 中使用 HttpURLConnection 发送 POST HTTP 请求

要使用 HttpURLConnection 通过 POST 方法发送 HTTP 请求,我们必须设置请求属性。下面的示例演示了通过 HttpURLConnection 和 POST 方法发送 HTTP 请求,需要 URL 和 URL 参数。

package delftstack;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class POST_HttpURLConnection {
  private static HttpURLConnection post_connection;
  public static void main(String[] args) throws IOException {
    // URL
    String Post_URL = "https://httpbin.org/post";
    // URL Parameters
    String Post_URL_Parameters = "name=Michelle&occupation=Secretory";
    // Get Bytes of parameters
    byte[] Post_Data = Post_URL_Parameters.getBytes(StandardCharsets.UTF_8);
    try {
      URL Demo_URL = new URL(Post_URL);
      post_connection = (HttpURLConnection) Demo_URL.openConnection();
      post_connection.setDoOutput(true);
      // Set the method
      post_connection.setRequestMethod("POST");
      // The request property
      post_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      // write the bytes or the data to the URL connection.
      try (DataOutputStream Data_Output_Stream =
               new DataOutputStream(post_connection.getOutputStream())) {
        Data_Output_Stream.write(Post_Data);
      }

      // Get the content
      StringBuilder Post_Webpage_Content;
      try (BufferedReader webpage =
               new BufferedReader(new InputStreamReader(post_connection.getInputStream()))) {
        String Webpage_line;
        Post_Webpage_Content = new StringBuilder();
        while ((Webpage_line = webpage.readLine()) != null) {
          Post_Webpage_Content.append(Webpage_line);
          Post_Webpage_Content.append(System.lineSeparator());
        }
      }
      System.out.println(Post_Webpage_Content.toString());

    } finally {
      post_connection.disconnect();
    }
  }
}

输出:

{
    "args": {},
    "data": "",
    "files": {},
    "form": {
        "name": "Michelle",
        "occupation": "Secretory"
    },
    "headers": {
        "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
        "Content-Length": "34",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "httpbin.org",
        "User-Agent": "Java/17.0.2",
        "X-Amzn-Trace-Id": "Root=1-62308f8e-7aa124b15d6d3cd1114d6463"
    },
    "json": null,
    "origin": "182.182.126.98",
    "url": "https://httpbin.org/post"
}

在 Java 中使用 Apache HttpClient 来发送 HTTP 请求

要首先使用 Apache HttpClient,你必须将库添加到你的项目下载 Apache HttpClient 并将 jar 文件添加到你的项目构建路径库中。

在 Java 中使用 Apache HttpClient 发送 GET HTTP 请求

我们也可以使用 Apache HttpClient 并通过 GET 方法发送 HTTP 请求来获取内容。Apache HttpClient 比 HttpURLConnection 更容易。

例子:

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class Get_HttpClient {
  public static void main(String[] args) throws IOException {
    try (CloseableHttpClient Apache_Get_Client = HttpClientBuilder.create().build()) {
      // Create a GET request
      HttpGet Apache_Get_Request = new HttpGet("https://www.delftstack.com/");
      // execute the request to get the response
      HttpResponse Apache_Get_Response = Apache_Get_Client.execute(Apache_Get_Request);
      // Get the content
      BufferedReader Webpage =
          new BufferedReader(new InputStreamReader(Apache_Get_Response.getEntity().getContent()));
      StringBuilder Webpage_Content = new StringBuilder();
      String Webpage_Content_Line;
      while ((Webpage_Content_Line = Webpage.readLine()) != null) {
        Webpage_Content.append(Webpage_Content_Line);
        Webpage_Content.append(System.lineSeparator());
      }
      System.out.println(Webpage_Content);
    }
  }
}

输出:

Apache HttpClient

在 Java 中使用 Apache HttpClient 发送 POST HTTP 请求

我们可以使用 Apache HttpClient 并通过 POST 方法发送 HTTP 请求来获取内容。

例子:

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class Post_HttpClient {
  public static void main(String[] args) throws IOException {
    try (CloseableHttpClient Apache_Post_Client = HttpClientBuilder.create().build()) {
      // Create a post request
      HttpPost Apache_Post_Request = new HttpPost("https://www.delftstack.com/");
      // pass parameters or set entity
      Apache_Post_Request.setEntity(new StringEntity("This is delftstack"));
      // execute the request to get the response
      HttpResponse Apache_Post_Response = Apache_Post_Client.execute(Apache_Post_Request);
      // Get the content
      BufferedReader Webpage =
          new BufferedReader(new InputStreamReader(Apache_Post_Response.getEntity().getContent()));
      StringBuilder Webpage_Content = new StringBuilder();
      String Webpage_line;
      while ((Webpage_line = Webpage.readLine()) != null) {
        Webpage_Content.append(Webpage_line);
        Webpage_Content.append(System.lineSeparator());
      }
      System.out.println(Webpage_Content);
    }
  }
}

输出:

Apache HttpClient

Java 11 及之前的版本具有 HttpClient 的内置功能,新版本不支持该功能。HttpClient 与 Apache HTTPClient 不同。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - Java HTTP