让我们假设这个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());
}
}
}