Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache HTTP Client, POST request. How to correctly set request parameters?

I'm using Apache HTTP Client and I need to send a POST request to my servlet. When the request is sent my servlet does not receive any parameters (in the HttpServletRequest).

Here is the client program code:

// Engage the HTTP client
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
    HttpPost httpPost = new HttpPost("http://localhost:8080/test-json-web/JSONReceiverServlet");

    // Setup the request parameters
    HttpParams params = new BasicHttpParams();
    params.setParameter("taskdef", task1JsonString);
    httpPost.setParams(params);

    // Make the request
    response = httpclient.execute(httpPost);

    HttpEntity responseEntity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if(responseEntity != null) {
        System.out.println("Response content length: " + responseEntity.getContentLength());
    }

    String jsonResultString = EntityUtils.toString(responseEntity);
    EntityUtils.consume(responseEntity);
    System.out.println("----------------------------------------");
    System.out.println("result:");
    System.out.println();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    httpclient.getConnectionManager().shutdown();
}

How to correctly set POST request parameters so that servlet actually receives them?

like image 961
Dmitry Avatar asked Aug 15 '11 17:08

Dmitry


2 Answers

try this:

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
like image 74
swenker Avatar answered Nov 12 '22 10:11

swenker


Set "Content-Type" header to "application/x-www-form-urlencoded"

like image 26
malah Avatar answered Nov 12 '22 09:11

malah