在Java中发送HTTP POST请求

问题描述 投票:0回答:13

让我们假设这个 URL...

http://www.example.com/page.php?id=10            

(这里需要在POST请求中发送id)

我想将

id = 10
发送到服务器的
page.php
,服务器以 POST 方法接受它。

我如何在 Java 中执行此操作?

我试过这个:

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

但我还是不知道如何通过 POST 发送

java http post
13个回答
385
投票

更新答案

由于原始答案中的某些类在较新版本的 Apache HTTP Components 中已弃用,因此我发布此更新。

顺便说一句,您可以在此处访问完整文档以获取更多示例。

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

原答案

我建议使用 Apache HttpClient。它更快、更容易实施。

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

有关更多信息,请检查此 URL:http://hc.apache.org/


254
投票

在普通 Java 中发送 POST 请求很容易。从

URL
开始,我们需要使用
URLConnection
将其转换为
url.openConnection();
。之后,我们需要将其转换为
HttpURLConnection
,这样我们就可以访问它的
setRequestMethod()
方法来设置我们的方法。我们最后说我们将通过连接发送数据。

URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);

然后我们需要说明我们要发送的内容:

发送简单表格

来自 http 表单的普通 POST 具有“定义良好”的格式。我们需要将输入转换为这种格式: Map<String,String> arguments = new HashMap<>(); arguments.put("username", "root"); arguments.put("password", "sjh76HSn!"); // This is a fake password obviously StringJoiner sj = new StringJoiner("&"); for(Map.Entry<String,String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length;

然后我们可以将表单内容附加到具有正确标头的 http 请求中并发送。

http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try(OutputStream os = http.getOutputStream()) { os.write(out); } // Do something with http.getInputStream()

发送 JSON

我们也可以使用java发送json,这也很简单:

byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8); int length = out.length; http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); http.connect(); try(OutputStream os = http.getOutputStream()) { os.write(out); } // Do something with http.getInputStream()

请记住,不同的服务器接受不同的 json 内容类型,请参阅
this

问题。

使用java post发送文件

由于格式更复杂,发送文件可能更难处理。我们还将添加对以字符串形式发送文件的支持,因为我们不想将文件完全缓冲到内存中。

为此,我们定义了一些辅助方法:

private void sendFile(OutputStream out, String name, InputStream in, String fileName) { String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8") + "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n"; out.write(o.getBytes(StandardCharsets.UTF_8)); byte[] buffer = new byte[2048]; for (int n = 0; n >= 0; n = in.read(buffer)) out.write(buffer, 0, n); out.write("\r\n".getBytes(StandardCharsets.UTF_8)); } private void sendField(OutputStream out, String name, String field) { String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n"; out.write(o.getBytes(StandardCharsets.UTF_8)); out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8)); out.write("\r\n".getBytes(StandardCharsets.UTF_8)); }

然后我们可以使用这些方法来创建多部分发布请求,如下所示:

String boundary = UUID.randomUUID().toString(); byte[] boundaryBytes = ("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8); byte[] finishBoundaryBytes = ("--" + boundary + "--").getBytes(StandardCharsets.UTF_8); http.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary); // Enable streaming mode with default settings http.setChunkedStreamingMode(0); // Send our fields: try(OutputStream out = http.getOutputStream()) { // Send our header (thx Algoman) out.write(boundaryBytes); // Send our first field sendField(out, "username", "root"); // Send a seperator out.write(boundaryBytes); // Send our second field sendField(out, "password", "toor"); // Send another seperator out.write(boundaryBytes); // Send our file try(InputStream file = new FileInputStream("test.txt")) { sendFile(out, "identification", file, "text.txt"); } // Finish the request out.write(finishBoundaryBytes); } // Do something with http.getInputStream()



114
投票


30
投票
另外,我也很难弄清楚如何使用 Java 库读取

HttpResponse


这是更完整的代码:

/* * Create the POST request */ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://example.com/"); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user", "Bob")); try { httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { // writing error to Log e.printStackTrace(); } /* * Execute the HTTP Request */ try { HttpResponse response = httpClient.execute(httpPost); HttpEntity respEntity = response.getEntity(); if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); } } catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // writing exception to log e.printStackTrace(); }



17
投票

Request.Post("http://www.example.com/page.php") .bodyForm(Form.form().add("id", "10").build()) .execute() .returnContent();

看看
Fluent API


11
投票

然后您将看到以下窗口来选择您希望请求代码使用的语言:


5
投票

String postURL = "http://www.example.com/page.php"; HttpPost post = new HttpPost(postURL); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id", "10")); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(ent); HttpClient client = new DefaultHttpClient(); HttpResponse responsePOST = client.execute(post);

你已经完成了。现在您可以使用
responsePOST

。 获取字符串形式的响应内容:


BufferedReader reader = new BufferedReader(new InputStreamReader(responsePOST.getEntity().getContent()), 2048); if (responsePOST != null) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { System.out.println(" line : " + line); sb.append(line); } String getResponseString = ""; getResponseString = sb.toString(); //use server output getResponseString as string value. }



5
投票

public void post(String uri, String data) throws Exception { HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(uri)) .POST(BodyPublishers.ofString(data)) .build(); HttpResponse<?> response = client.send(request, BodyHandlers.discarding()); System.out.println(response.statusCode());

这里有更多信息:
https://openjdk.java.net/groups/net/httpclient/recipes.html#post


4
投票

okhttp 的源代码可以在这里找到

https://github.com/square/okhttp

. 如果您正在编写 pom 项目,请添加此依赖项

<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version> </dependency>

如果不是,只需在互联网上搜索“download okhttp”即可。将出现几个结果,您可以在其中下载 jar。

你的代码:

import okhttp3.*; import java.io.IOException; public class ClassName{ private void sendPost() throws IOException { // form parameters RequestBody formBody = new FormBody.Builder() .add("id", 10) .build(); Request request = new Request.Builder() .url("http://www.example.com/page.php") .post(formBody) .build(); OkHttpClient httpClient = new OkHttpClient(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); // Get response body System.out.println(response.body().string()); } } }



4
投票
java.net.http.HttpClient

以更少的代码发出 HTTP 请求。 var values = new HashMap<String, Integer>() {{ put("id", 10); }}; var objectMapper = new ObjectMapper(); String requestBody = objectMapper .writeValueAsString(values); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://www.example.com/abc")) .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());



1
投票
HttpURLConnection.setRequestMethod("POST")

HttpURLConnection.setDoOutput(true);
实际上只需要后者,因为 POST 就成为默认方法。
    


1
投票
http-request

构建在 apache http api 上。 HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class) .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build(); public void send(){ String response = httpRequest.execute("id", "10").get(); }



0
投票
11

或更高版本(Android 上除外)具有新的 HTTP 客户端 API var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true"); var client = HttpClient.newHttpClient(); 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());

同一个请求异步执行:

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

要以多部分 (
multipart/form-data

) 或 url 编码 (

application/x-www-form-urlencoded
) 格式发送表单数据,请参阅
此解决方案
请参阅

本文

,了解有关 HTTP 客户端 API 的示例和更多信息。 对于 Java 标准库 HTTP

server

,请参阅 这篇文章

© www.soinside.com 2019 - 2024. All rights reserved.