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