【问题标题】:Apache HTTP Client Post appears to work but variable not receivedApache HTTP Client Post 似乎可以工作,但未收到变量
【发布时间】:2014-01-11 16:36:43
【问题描述】:

我有以下代码执行 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"]);
?>

但是打印出一个索引未定义的错误

【问题讨论】:

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


    【解决方案1】:

    您正在设置构建 URI 的 URI 的查询参数,您的 URI 如 @987654321@

    你需要用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 发送凭据。

    【讨论】:

    • hmm 给了我和以前一样的错误?您能否发布一个使用基本身份验证的示例?
    • 然后您可以检索用户名并使用 $_SERVER['PHP_AUTH_USER'] 和 $_SERVER['PHP_AUTH_PW'] 传递服务器端
    猜你喜欢
    • 2013-11-27
    • 2015-03-03
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多