Apache HTTP Client Post似乎有效,但未收到变量

时间:2014-01-11 16:36:43

标签: java php web-services post apache-commons-httpclient

我有以下代码执行httpclient帖子请求

    public void upload() throws Exception{

    //HTTP POST Service
    try{
        HttpClient httpclient = HttpClientBuilder.create().build();         
        URI uri = new URIBuilder()
        .setScheme("http")
        .setHost("www.mysite.com")
        .setPath("/mypage.php")
        .setParameter("Username", userID)
        .setParameter("Password", password)
        .build();
        HttpPost httppost = new HttpPost(uri);
        httpclient.execute(httppost);

        BasicHttpContext localContext = new BasicHttpContext();
        HttpResponse response = httpclient.execute(httppost, localContext);
        HttpUriRequest currentReq = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost currentHost = (HttpHost)localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        String currentUrl = currentHost.toURI() + currentReq.getURI();        
        System.out.println(currentUrl);
        System.out.println(response);
        HttpEntity httpEntity = response.getEntity();
        String str = "";
        if (httpEntity != null) {
            str = EntityUtils.toString(httpEntity);
            System.out.println(str);
        }

    }catch (Exception e) {
        e.printStackTrace();
    }
}

返回

HTTP/1.1 200 OK [Date: Sat, 11 Jan 2014 16:17:22 GMT, Server: Apache, Expires: Thu, 19 Nov 1981 08:52:00 GMT, Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, Pragma: no-cache, Vary: Accept-Encoding, Keep-Alive: timeout=10, max=30, Content-Type: text/html, Via: 1.1 NDC1-B2-CE01, Connection: keep-alive]

好像一切都运行良好但我的另一端的php脚本似乎没有拿起变量。

我尝试了一些简单的事情:

<?php
   error_log($_POST["Username"]);
?>

但是打印索引未定义错误

1 个答案:

答案 0 :(得分:1)

您正在设置URI的查询参数,该URI构建URI,例如http://www.mysite.com/mypage.php?Username=userId&Password=pass

您需要使用NameValuePair设置HttpPost的参数。

HttpPost post = new HttpPost("http://www.mysite.com/mypage.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", userId));
params.add(new BasicNameValuePair("Password", pass));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = post.execute(post);

此外,我建议使用Authorization标头处理身份验证,例如Basic authentication以及通过HTTPS发送凭据。