Adding parameter to HttpPost on Apache's httpclient

24,086

Solution 1

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

Solution 2

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.

Share:
24,086
pokeRex110
Author by

pokeRex110

Updated on July 09, 2022

Comments

  • pokeRex110
    pokeRex110 almost 2 years

    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

  • Rahul Lodha
    Rahul Lodha about 8 years
    this question is asked for http get request. you cannot setEntity for a http get request
  • Ben
    Ben about 8 years
    Should be using LinkedList instead of ArrayList
  • Dacav
    Dacav over 7 years
    DefaultHttpClient is deprecated.
  • Dacav
    Dacav over 7 years
    @Benedictus, why?
  • Ben
    Ben over 7 years
    ArrayList's are good for holding non-changing data, and quick indexing. But are slow and space-consuming when you add or remove members. The LinkedList structure is more suitable in this scenario.