3

I'm using the apache http library and need to know how to add a parameter to an HTTP GET request. I've looked over How to add parameters to a HTTP GET request in Android? but the accepted answer for that adds parameters to an HTTP POST. This is my code so far but it is not working.

HttpGet get = new HttpGet("https://server.com/stuff");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpParams p = get.getParams();
p.setParameter("length", "5");
get.setParams(p);
Community
  • 1
  • 1
mpatten
  • 71
  • 1
  • 2
  • 10
  • Please explain how it is not working - does it not compile, crash, or just not return the expected results? – iagreen Jan 11 '13 at 14:49
  • Adding a get parameter is trivial. You can just make it `new HttpGet("https://server.com/stuff?id=" + 123);` for example – Alpay Jan 11 '13 at 14:51
  • 1
    use "http://server.com/stuff" + URLEncodedUtils.format(nameValuePairs, "utf-8"); HttpParams is for http parameters, which are protocol related. – njzk2 Jan 11 '13 at 14:55
  • the server acts as if it is not receiving a parameter at all when i use the above method. I'll try njzk2's answer – mpatten Jan 11 '13 at 15:13

2 Answers2

14
String url = "https://server.com/stuff"
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpClient httpClient = new DefaultHttpClient();
String paramsString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
HttpGet httpGet = new HttpGet(url + "?" + paramsString);
HttpResponse response = httpClient.execute(httpGet);

EDIT: Since Android SDK v22, the type NameValuePair is deprecated. I recommend using Volley, an HTTP library that makes networking for Android apps easier and most importantly, faster.

Andrea Motto
  • 1,540
  • 21
  • 38
8

unlike POST, GET sends the parameters under the url like this:

http://myurl.com?variable1=value&variable2=value2

Where: the parameters area start from the question mark and on so the variable1 is the first param and it has "value" value...

See here for more informations.

So what you need to do is just build an url that contains also these parameters according to server needs.

EDIT:

In your case :

HttpGet get = new HttpGet("https://server.com/stuff?count=5&length=5");
...

Where: count=5 and length=5 are the parameters and the "?" mark is the beginning of the parameters definition... I hope that helps.

Cata
  • 11,133
  • 11
  • 65
  • 86
  • This worked, I just wish there was an easier way than building a string. – mpatten Jan 11 '13 at 15:21
  • Well you could design a helper method to do that.. and using a list of value and pair object you could generate the url... and also encode it by your needs... – Cata Jan 11 '13 at 15:39