pokeRex110
pokeRex110

Reputation: 855

Adding parameter to HttpPost on Apache's httpclient

I am trying to set some Http parameters in the HttpPost object.

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

It looks like the parameter is not set at all. Do you have any idea why this is happening?

Thank you

Upvotes: 11

Views: 25584

Answers (2)

joker
joker

Reputation: 158

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);

Upvotes: 11

Cyril N.
Cyril N.

Reputation: 39859

For those who hopes to find the answer using HttpGet, here's one (from 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());

NOTE: This doesn't take in consideration the state of your_url : if there is already some parameters, if it already contains a "?", etc. I assume you know how to code/search and will adapt regarding your case.

Upvotes: 26

Related Questions