让我们假设这个URL…

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

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

我想将id = 10发送到服务器的page.php,该服务器在POST方法中接受它。

我如何从Java中做到这一点?

我试了一下:

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

但是我仍然不知道如何通过POST发送它


当前回答

第一个答案很好,但我必须添加try/catch以避免Java编译器错误。 另外,我在弄清楚如何使用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();
}

其他回答

使用Apache HTTP Components的一种简单方法是

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

看一看Fluent API

我建议使用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();
}

更新后的答案

由于原始答案中的一些类在Apache HTTP组件的新版本中已弃用,所以我发布了此更新。

顺便说一下,您可以在这里访问更多示例的完整文档。

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/

轻松使用java.net:

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

使用okhttp:

okhttp的源代码可以在这里找到https://github.com/square/okhttp。

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

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

如果不是,可以在网上搜索“下载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());
                }
        }
    }