在Apache的httpclient上向HttpPost添加参数

时间:2012-02-20 14:04:23

标签: java apache parameters get httpclient

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

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

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

谢谢

2 个答案:

答案 0 :(得分:26)

对于那些希望使用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的状态:如果已经有一些参数,如果它已经包含“?”等,我假设你知道如何编码/搜索并适应您的情况。

答案 1 :(得分:8)

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);
相关问题