让我们假设这个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发送它


当前回答

用post请求发送参数的最简单方法:

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.
}

其他回答

第一个答案很好,但我必须添加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();
}

从java 11开始,HTTP请求可以通过使用java.net.http.HttpClient进行,代码更少。

    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());

调用HttpURLConnection.setRequestMethod("POST")和HttpURLConnection.setDoOutput(true);实际上只需要后者,因为POST将成为默认方法。

轻松使用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

我建议使用Postman来生成请求代码。简单地使用Postman进行请求,然后点击code选项卡:

然后你会看到下面的窗口,选择你想要的请求代码的语言: