试图添加一个http参数,但它不起作用

时间:2013-03-18 15:36:57

标签: java apache http post

HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpMethod = new HttpPost(this.transformURL(request));
            BasicHttpParams params = new BasicHttpParams();
            params.setParameter("name", name);
            httpMethod.setParams(params);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            httpclient.execute(httpMethod, responseHandler);
        }catch{
           LOG.error("Error");
        } finally { 
          httpclient.getConnectionManager().shutdown();
        }

我有上面的代码,我试图传递一个名称变量作为参数,以便通过request.getParameter("name")在另一种方法中获取。

它似乎不起作用,当我调试时我可以看到参数设置但是当我按照它执行到下一个执行的方法时,它不会获取参数。

有什么建议吗?

编辑:

我添加了这个并且效果很好

 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("name", request.getParameter("name")));
            httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

1 个答案:

答案 0 :(得分:0)

您检查过this example了吗?它会像您一样使用班级BasicNameValuePair而不是BasicHttpParams

此外,documentation for the version 3.x of HttpClient会这样做:

    PostMethod post = new PostMethod("http://jakarata.apache.org/");
    NameValuePair[] data = {
      new NameValuePair("user", "joe"),
      new NameValuePair("password", "bloggs")
    };
    post.setRequestBody(data);
    // execute method and handle any error responses.
    ...
    InputStream in = post.getResponseBodyAsStream();
    // handle response.

更新BasicHttpParams类是HttpParams接口的一个实现,正如下面@Perception所述,是一组属性“,用于自定义HTTP客户端“。从HttpParams javadoc“HttpParams预计将用于'一次写入 - 多次读取'模式。一旦初始化,HTTP参数在HTTP消息处理过程中不会发生变异。”