Apache HTTP客户端,POST请求.如何正确设置请求参数?
问题描述:
我正在使用Apache HTTP Client,需要将POST请求发送到我的servlet.
发送请求时,我的servlet没有收到任何参数(在HttpServletRequest
中).
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
).
这是客户端程序代码:
// 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();
}
如何正确设置POST请求参数,以便servlet实际接收它们?
How to correctly set POST request parameters so that servlet actually receives them?
答
尝试一下:
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));