【问题标题】:HttpServletRequest get no parameters from my httppostHttpServletRequest 没有从我的 httppost 获取任何参数
【发布时间】: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 可以看到参数?

【问题讨论】:

    标签: android tomcat servlets


    【解决方案1】:

    在 HTML 中,当我们有“http://host/path?user=uname&passwd=pass”之类的内容时,我们将问号后面的部分 (user=uname&passwd=pass) 称为“表单数据”。“表单数据” " 可以在问号之后附加到 URL 的末尾(如上),用于 GET 请求,或者在单独的行上发送到服务器,用于 POST 请求。“表单数据”被拆分为参数。当我们使用 GET 时,参数用 & 分隔。

    在我们的例子中,HttpPost 和 HttpGet 类扩展了实现 setParams 方法的 AbstractHttpMessage。这个方法对于 GET 和 POST 是一样的,但是只对 GET 起作用!在 GET 的情况下,参数放在 URL 中。在 POST 的情况下,您需要将参数的实体设置在“单独的行”上。

    在服务器端使用 servlet 时,getParameters 非常聪明,可以找到 GET 和 POST 的参数。

    这就是为什么在服务器端我们不需要更改获取参数的代码!

    希望我能帮上忙!

    【讨论】:

    • 这真是一个很好的解释!谢谢,这正是我想要的。
    猜你喜欢
    • 2014-04-07
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多