Java httpPost没有正确发布数据(Apache库)?

时间:2012-10-22 20:40:24

标签: java apache entity http-post

快速问题,因为我尝试了很多调试选项,没有人帮助识别问题。我正在使用Java和Apache HttpPost库。

我的httpGet和httpHead目前工作正常,但我无法让httpPost正确发送变量。我在服务器上设置了一个调试PHP脚本,只是转储$_POST的内容。如果我在终端中执行卷曲请求,则工作正常。

代码段:

    // create new HttpPost object
    postRequest = new HttpPost(url);

    // add post variables
    postRequest.setEntity(new StringEntity(body, ContentType.TEXT_HTML));

    // execute request
    response = executeRequest(postRequest);

String变量“body”只是一个字符串,当前包含“test = testing”。这个PHP调试脚本的输出:

<?php 

  echo "Input Stream: ";

  var_dump(file_get_contents('php://input'));

  echo "POST Variables: ";

  var_dump($_POST);

?>

是:

Input Stream: string(12) "test=testing"
POST Variables: array(0) {
}

有谁知道为什么它没有被提取并转储到$_POST变量中?因为我花了好几个小时才非常恼火!

任何帮助将不胜感激:)谢谢

1 个答案:

答案 0 :(得分:0)

请参阅Access all entries of HttpParams

要构建包含参数的URI,请使用:

NameValuePair nvp = new BasicNameValuePair("test", "testing");
String query = URLEncodedUtils.format(nvp, "utf-8"); // use your favourite charset here
URI uri = new URI("http://localhost/app?" + query;
HttpPost postReq = new HttpPost(uri);
httpClient.execute(postReq);

这将导致:http://localhost/app?test=testing被请求。