Search code examples
javaphpweb-servicespostapache-commons-httpclient

Apache HTTP Client Post appears to work but variable not received


I have the following code that executes a httpclient post request

    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();
    }
}

which returns

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]

As if everything had worked fine but my php script on the other end doesn't seem to pick up the variable.

I've tried something as simple as:

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

But get an index undefined error printed


Solution

  • You are setting the query parameters of the URI which builds a URI your URI like http://www.mysite.com/mypage.php?Username=userId&Password=pass

    You need to set the parameters of the HttpPost with NameValuePair.

    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);
    

    Additionally, I would recommend handling authentication with an Authorization header, such as Basic authentication as well as sending credentials over HTTPS.