【发布时间】:2011-10-07 15:42:42
【问题描述】:
我有一个好奇的问题。我在 Android 中有一个 HttpPost 请求,看起来像这样:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(getString(R.string.url));
//This code does not work
HttpParams params = new BasicHttpParams();
params.setParameter("type", "20");
post.setParams(params);
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
在我的服务器端,我有一个 servlet 用于侦听请求并解析参数:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
当我执行这段代码时,servlet 根本看不到任何参数。但是如果我用这段代码替换整个“参数”块:
//This code works
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("type", "20"));
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
我的 servlet 可以解析参数。这不是问题,我只是要使用实体,但我的问题是,为什么我的 servlet 不能从第一个代码块中获取参数? setParams 有什么问题?如果我将参数设置为实体,为什么 servlet 可以看到参数?
【问题讨论】: