在Java中,如何撰写HTTP请求消息并将其发送到HTTP web服务器?


当前回答

如果您正在使用Java 11或更新版本(Android除外),而不是遗留的HttpUrlConnection类,您可以使用Java 11新的HTTP客户端API。

一个示例GET请求:

var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
var client = HttpClient.newHttpClient();
var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .header("accept", "application/json")
        .GET()
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());

同一请求异步执行:

var responseAsync = client
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);
// responseAsync.join(); // Wait for completion

一个POST请求的例子:

var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .version(HttpClient.Version.HTTP_2)
        .timeout(Duration.ofMinutes(1))
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer fake")
        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());

要以多部分(multipart/form-data)或url编码(application/x-www-form-urlencoded)格式发送表单数据,请参阅此解决方案。

有关HTTP客户端API的示例和更多信息,请参阅本文。

对于Java标准库HTTP服务器,请参阅这篇文章。

其他回答

Apache HttpComponents。这两个模块的例子——HttpCore和HttpClient会让你马上开始。

并不是说HttpUrlConnection是一个糟糕的选择,HttpComponents将抽象出大量繁琐的编码。如果你真的想用最少的代码来支持大量的HTTP服务器/客户端,我推荐这样做。顺便说一下,HttpCore可以用于功能最少的应用程序(客户端或服务器),而HttpClient用于需要支持多种身份验证方案、cookie支持等的客户端。

我知道其他人会推荐Apache的http-客户端,但是它增加了复杂性(例如,更多可能出错的东西),这是很少被保证的。对于简单的任务,可以使用java.net.URL。

URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
  /* Now read the retrieved document from the stream. */
  ...
} finally {
  is.close();
}

如果您正在使用Java 11或更新版本(Android除外),而不是遗留的HttpUrlConnection类,您可以使用Java 11新的HTTP客户端API。

一个示例GET请求:

var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
var client = HttpClient.newHttpClient();
var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .header("accept", "application/json")
        .GET()
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());

同一请求异步执行:

var responseAsync = client
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println);
// responseAsync.join(); // Wait for completion

一个POST请求的例子:

var request = HttpRequest
        .newBuilder()
        .uri(uri)
        .version(HttpClient.Version.HTTP_2)
        .timeout(Duration.ofMinutes(1))
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer fake")
        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
        .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());

要以多部分(multipart/form-data)或url编码(application/x-www-form-urlencoded)格式发送表单数据,请参阅此解决方案。

有关HTTP客户端API的示例和更多信息,请参阅本文。

对于Java标准库HTTP服务器,请参阅这篇文章。

下面是一个完整的Java 7程序:

class GETHTTPResource {
  public static void main(String[] args) throws Exception {
    try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://example.com/").openStream())) {
      System.out.println(s.useDelimiter("\\A").next());
    }
  }
}

新的try-with-resources将自动关闭Scanner,而Scanner将自动关闭InputStream。

您可以使用java.net.HttpUrlConnection。

示例(来自这里),并进行了改进。包括在链接腐烂的情况下:

public static String executePost(String targetURL, String urlParameters) {
  HttpURLConnection connection = null;

  try {
    //Create connection
    URL url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", 
        Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");  

    connection.setUseCaches(false);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
    String line;
    while ((line = rd.readLine()) != null) {
      response.append(line);
      response.append('\r');
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}