【问题标题】:Adding parameter to HttpPost on Apache's httpclient在 Apache 的 httpclient 上向 HttpPost 添加参数
【发布时间】:2012-02-20 14:04:23
【问题描述】:

我正在尝试在 HttpPost 对象中设置一些 Http 参数。

HttpPost post=new HttpPost(url);
HttpParams params=new BasicHttpParams();
params.setParameter("param", "value");
post.setParams(params);
HttpResponse response = client.execute(post);

看起来参数根本没有设置。你知道为什么会这样吗?

谢谢

【问题讨论】:

  • HttpPost get!它是 POST 还是 GET?
  • 您在描述和标题中说 HttpGet,但您的代码却说 HttpPost。我刚刚编辑它是正确的

标签: java apache parameters get httpclient


【解决方案1】:

对于那些希望使用 HttpGet 找到答案的人,这里有一个(来自https://stackoverflow.com/a/4660576/330867):

StringBuilder requestUrl = new StringBuilder("your_url");

String querystring = URLEncodedUtils.format(params, "utf-8");
requestUrl.append("?");
requestUrl.append(querystring);

HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(requestUrl.toString());

注意:这没有考虑your_url 的状态:如果已经有一些参数,如果它已经包含一个“?”等等。我假设你知道如何代码/搜索,并将根据您的情况进行调整。

【讨论】:

  • DefaultHttpClient 已弃用。
【解决方案2】:
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("param", "value"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpClient.execute(httpPost);

【讨论】:

  • 这个问题是针对http get请求提出的。您不能为 http get 请求设置实体
  • 应该使用 LinkedList 而不是 ArrayList
  • @Benedictus,为什么?
  • ArrayList 适合保存不变的数据和快速索引。但是在添加或删除成员时会很慢且占用空间。 LinkedList 结构更适合这种场景。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多