让我们假设这个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());
}
}
}
更新后的答案
由于原始答案中的一些类在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/