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


当前回答

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

其他回答

String rawData = "id=10";
String type = "application/x-www-form-urlencoded";
String encodedData = URLEncoder.encode( rawData, "UTF-8" ); 
URL u = new URL("http://www.example.com/page.php");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf(encodedData.length()));
OutputStream os = conn.getOutputStream();
os.write(encodedData.getBytes());

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

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

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

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

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