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?
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));
Set "Content-Type" header to "application/x-www-form-urlencoded"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With