{% raw %}

Java HTTP GET/POST 请求

原文:http://zetcode.com/java/getpostrequest/

本教程显示了如何使用 Java 发送 GET 和 POST 请求。 我们使用内置的HttpURLConnection类以及标准的 Java 和 Apache HttpClient类。

HTTP

超文本传输协议(HTTP)是用于分布式协作超媒体信息系统的应用协议。 HTTP 是万维网数据通信的基础。

在示例中,我们使用httpbin.org(这是一个免费的 HTTP 请求和响应服务),以及webcode.me(这是一个用于测试的小型 HTML 页面)。

HTTP GET

HTTP GET 方法请求指定资源的表示形式。 使用 GET 的请求应仅检索数据。

HTTP POST

HTTP POST 方法将数据发送到服务器。 在上载文件或提交完整的 Web 表单时,通常使用它。

Java 11 HttpClient的 GET 请求

从 Java 11 开始,我们可以使用java.net.http.HttpClient

com/zetcode/GetRequestJava11.java

  1. package com.zetcode;
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import java.net.http.HttpClient;
  5. import java.net.http.HttpRequest;
  6. import java.net.http.HttpResponse;
  7. public class GetRequestJava11 {
  8. public static void main(String[] args) throws IOException, InterruptedException {
  9. HttpClient client = HttpClient.newHttpClient();
  10. HttpRequest request = HttpRequest.newBuilder()
  11. .uri(URI.create("http://webcode.me"))
  12. .build();
  13. HttpResponse<String> response = client.send(request,
  14. HttpResponse.BodyHandlers.ofString());
  15. System.out.println(response.body());
  16. }
  17. }

我们向webcode.me网页创建 GET 请求。

  1. HttpClient client = HttpClient.newHttpClient();

使用newHttpClient()工厂方法创建一个新的HttpClient

  1. HttpRequest request = HttpRequest.newBuilder()
  2. .uri(URI.create("http://webcode.me"))
  3. .build();

我们建立对该网页的同步请求。 默认方法是 GET。

  1. HttpResponse<String> response = client.send(request,
  2. HttpResponse.BodyHandlers.ofString());
  3. System.out.println(response.body());

我们发送请求并检索响应的内容,然后将其打印到控制台。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>My html page</title>
  7. </head>
  8. <body>
  9. <p>
  10. Today is a beautiful day. We go swimming and fishing.
  11. </p>
  12. <p>
  13. Hello there. How are you?
  14. </p>
  15. </body>
  16. </html>

这是输出。

Java 11 HttpClient的 Java HTTP POST 请求

下一个示例使用 Java 11 HttpClient创建 POST 请求。

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.9.9.3</version>
  5. </dependency>

我们需要jackson-databind依赖项。

com/zetcode/PostRequestJava11.java

  1. package com.zetcode;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import java.io.IOException;
  4. import java.net.URI;
  5. import java.net.http.HttpClient;
  6. import java.net.http.HttpRequest;
  7. import java.net.http.HttpResponse;
  8. import java.util.HashMap;
  9. public class HttpClientPost {
  10. public static void main(String[] args) throws IOException, InterruptedException {
  11. var values = new HashMap<String, String>() {{
  12. put("name", "John Doe");
  13. put ("occupation", "gardener");
  14. }};
  15. var objectMapper = new ObjectMapper();
  16. String requestBody = objectMapper
  17. .writeValueAsString(values);
  18. HttpClient client = HttpClient.newHttpClient();
  19. HttpRequest request = HttpRequest.newBuilder()
  20. .uri(URI.create("https://httpbin.org/post"))
  21. .POST(HttpRequest.BodyPublishers.ofString(requestBody))
  22. .build();
  23. HttpResponse<String> response = client.send(request,
  24. HttpResponse.BodyHandlers.ofString());
  25. System.out.println(response.body());
  26. }
  27. }

我们将 POST 请求发送到https://httpbin.org/post页面。

  1. var values = new HashMap<String, String>() {{
  2. put("name", "John Doe");
  3. put ("occupation", "gardener");
  4. }};
  5. var objectMapper = new ObjectMapper();
  6. String requestBody = objectMapper
  7. .writeValueAsString(values);

首先,我们使用 Jackson 的ObjectMapper构建请求主体。

  1. HttpClient client = HttpClient.newHttpClient();
  2. HttpRequest request = HttpRequest.newBuilder()
  3. .uri(URI.create("https://httpbin.org/post"))
  4. .POST(HttpRequest.BodyPublishers.ofString(requestBody))
  5. .build();

我们构建 POST 请求。 使用BodyPublishers.ofString()创建一个新的BodyPublisher。 它将高级 Java 对象转换为适合作为请求正文发送的字节缓冲区流。

  1. HttpResponse<String> response = client.send(request,
  2. HttpResponse.BodyHandlers.ofString());
  3. System.out.println(response.body());

我们发送请求并检索响应。

  1. {
  2. "args": {},
  3. "data": "{\"occupation\":\"gardener\",\"name\":\"John Doe\"}",
  4. "files": {},
  5. "form": {},
  6. "headers": {
  7. "Content-Length": "43",
  8. "Host": "httpbin.org",
  9. "User-Agent": "Java-http-client/12.0.1"
  10. },
  11. "json": {
  12. "name": "John Doe",
  13. "occupation": "gardener"
  14. },
  15. ...
  16. "url": "https://httpbin.org/post"
  17. }

这是输出。

使用HttpURLConnection的 Java HTTP GET 请求

以下示例使用HttpURLConnection创建 GET 请求。

com/zetcode/JavaGetRequest.java

  1. package com.zetcode;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class JavaGetRequest {
  8. private static HttpURLConnection con;
  9. public static void main(String[] args) throws IOException {
  10. var url = "http://webcode.me";
  11. try {
  12. var myurl = new URL(url);
  13. con = (HttpURLConnection) myurl.openConnection();
  14. con.setRequestMethod("GET");
  15. StringBuilder content;
  16. try (BufferedReader in = new BufferedReader(
  17. new InputStreamReader(con.getInputStream()))) {
  18. String line;
  19. content = new StringBuilder();
  20. while ((line = in.readLine()) != null) {
  21. content.append(line);
  22. content.append(System.lineSeparator());
  23. }
  24. }
  25. System.out.println(content.toString());
  26. } finally {
  27. con.disconnect();
  28. }
  29. }
  30. }

该示例使用 HTTP GET 请求检索网页。

  1. var url = "http://webcode.me";

我们检索此小型网页的内容。

  1. var myurl = new URL(url);
  2. con = (HttpURLConnection) myurl.openConnection();

创建到指定 URL 的连接。

  1. con.setRequestMethod("GET");

我们使用setRequestMethod()方法设置请求方法类型。

  1. try (BufferedReader in = new BufferedReader(
  2. new InputStreamReader(con.getInputStream()))) {

输入流是从 HTTP 连接对象创建的。 输入流用于读取返回的数据。

  1. content = new StringBuilder();

我们使用StringBuilder构建内容字符串。

  1. while ((line = in.readLine()) != null) {
  2. content.append(line);
  3. content.append(System.lineSeparator());
  4. }

我们使用readLine()逐行从输入流中读取数据。 每行都添加到StringBuilder中。 在每行之后,我们附加一个与系统有关的行分隔符。

  1. System.out.println(content.toString());

我们将内容打印到终端。

使用HttpURLConnection的 Java HTTP POST 请求

以下示例使用HttpURLConnection创建 POST 请求。

com/zetcode/JavaPostRequest.java

  1. package com.zetcode;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.nio.charset.StandardCharsets;
  9. public class JavaPostRequest {
  10. private static HttpURLConnection con;
  11. public static void main(String[] args) throws IOException {
  12. var url = "https://httpbin.org/post";
  13. var urlParameters = "name=Jack&occupation=programmer";
  14. byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
  15. try {
  16. var myurl = new URL(url);
  17. con = (HttpURLConnection) myurl.openConnection();
  18. con.setDoOutput(true);
  19. con.setRequestMethod("POST");
  20. con.setRequestProperty("User-Agent", "Java client");
  21. con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  22. try (var wr = new DataOutputStream(con.getOutputStream())) {
  23. wr.write(postData);
  24. }
  25. StringBuilder content;
  26. try (var br = new BufferedReader(
  27. new InputStreamReader(con.getInputStream()))) {
  28. String line;
  29. content = new StringBuilder();
  30. while ((line = br.readLine()) != null) {
  31. content.append(line);
  32. content.append(System.lineSeparator());
  33. }
  34. }
  35. System.out.println(content.toString());
  36. } finally {
  37. con.disconnect();
  38. }
  39. }
  40. }

该示例将 POST 请求发送到https://httpbin.org/post

  1. var urlParameters = "name=Jack&occupation=programmer";
  2. byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

我们将编写这两个键/值对。 我们将字符串转换为字节数组。

  1. var myurl = new URL(url);
  2. con = (HttpURLConnection) myurl.openConnection();

URL 的连接已打开。

  1. con.setDoOutput(true);

通过setDoOutput()方法,我们指示我们将数据写入 URL 连接。

  1. con.setRequestMethod("POST");

HTTP 请求类型通过setRequestMethod()设置。

  1. con.setRequestProperty("User-Agent", "Java client");

我们使用setRequestProperty()方法设置用户年龄属性。

  1. try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
  2. wr.write(postData);
  3. }

我们将字节或数据写入 URL 连接。

  1. StringBuilder content;
  2. try (var br = new BufferedReader(
  3. new InputStreamReader(con.getInputStream()))) {
  4. String line;
  5. content = new StringBuilder();
  6. while ((line = br.readLine()) != null) {
  7. content.append(line);
  8. content.append(System.lineSeparator());
  9. }
  10. }
  11. System.out.println(content.toString());

我们读取连接的输入流,并将检索到的内容写入控制台。

使用 Apache HttpClient的 Java HTTP GET 请求

以下示例使用 Apache HttpClient创建 GET 请求。

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.10</version>
  5. </dependency>

对于示例,我们需要此 Maven 依赖关系。

com/zetcode/ApacheHttpClientGet.java

  1. package com.zetcode;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.CloseableHttpClient;
  8. import org.apache.http.impl.client.HttpClientBuilder;
  9. public class ApacheHttpClientGet {
  10. public static void main(String[] args) throws IOException {
  11. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  12. var request = new HttpGet("http://webcode.me");
  13. HttpResponse response = client.execute(request);
  14. var bufReader = new BufferedReader(new InputStreamReader(
  15. response.getEntity().getContent()));
  16. var builder = new StringBuilder();
  17. String line;
  18. while ((line = bufReader.readLine()) != null) {
  19. builder.append(line);
  20. builder.append(System.lineSeparator());
  21. }
  22. System.out.println(builder);
  23. }
  24. }
  25. }

该示例发送 GET 请求以读取指定网页的主页。

  1. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

CloseableHttpClient是使用HttpClientBuilder构建的。

  1. var request = new HttpGet("http://webcode.me");

HttpGet用于创建 HTTP GET 请求。

  1. HttpResponse response = client.execute(request);

我们执行请求并获得响应。

  1. var bufReader = new BufferedReader(new InputStreamReader(
  2. response.getEntity().getContent()));

从响应对象中,我们读取内容。

  1. while ((line = bufReader.readLine()) != null) {
  2. builder.append(line);
  3. builder.append(System.lineSeparator());
  4. }

我们逐行读取内容并动态生成字符串消息。

Java HTTP POST 与 Apache HttpClient

以下示例使用HttpPost创建 POST 请求。

com/zetcode/ApacheHttpClientPost.java

  1. package com.zetcode;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import org.apache.http.HttpResponse;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClientBuilder;
  10. public class ApacheHttpClientPost {
  11. public static void main(String[] args) throws IOException {
  12. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  13. var request = new HttpPost("https://httpbin.org/post");
  14. request.setHeader("User-Agent", "Java client");
  15. request.setEntity(new StringEntity("My test data"));
  16. HttpResponse response = client.execute(request);
  17. var bufReader = new BufferedReader(new InputStreamReader(
  18. response.getEntity().getContent()));
  19. var builder = new StringBuilder();
  20. String line;
  21. while ((line = bufReader.readLine()) != null) {
  22. builder.append(line);
  23. builder.append(System.lineSeparator());
  24. }
  25. System.out.println(builder);
  26. }
  27. }
  28. }

The example sends a POST request to https://httpbin.org/post.

  1. var request = new HttpPost("https://httpbin.org/post");

HttpPost用于创建 POST 请求。

  1. request.setEntity(new StringEntity("My test data"));

setEntity()方法设置数据。

  1. request.setHeader("User-Agent", "Java client");

我们使用setHeader()方法为请求设置标头。

  1. HttpResponse response = client.execute(request);

我们执行请求并获得响应。

  1. var bufReader = new BufferedReader(new InputStreamReader(
  2. response.getEntity().getContent()));
  3. var builder = new StringBuilder();
  4. String line;
  5. while ((line = bufReader.readLine()) != null) {
  6. builder.append(line);
  7. builder.append(System.lineSeparator());
  8. }
  9. System.out.println(builder);

我们阅读响应并将其打印到终端。

在本教程中,我们使用HttpURLConnection以及标准 Java 和 Apache HttpClient在 Java 中创建了 GET 和 POST 请求。

您可能也对以下相关教程感兴趣: Python 请求教程Jsoup 教程Java 教程用 Java 读取网页Google Guava 简介

列出所有 Java 教程

{% endraw %}