How to add parameters to a HTTP GET request in Android?
I use a List of NameValuePair and URLEncodedUtils to create the url string I want.
protected String addLocationToUrl(String url){ if(!url.endsWith("?")) url += "?"; List<NameValuePair> params = new LinkedList<NameValuePair>(); if (lat != 0.0 && lon != 0.0){ params.add(new BasicNameValuePair("lat", String.valueOf(lat))); params.add(new BasicNameValuePair("lon", String.valueOf(lon))); } if (address != null && address.getPostalCode() != null) params.add(new BasicNameValuePair("postalCode", address.getPostalCode())); if (address != null && address.getCountryCode() != null) params.add(new BasicNameValuePair("country",address.getCountryCode())); params.add(new BasicNameValuePair("user", agent.uniqueId)); String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; return url;}
As of HttpComponents 4.2+
there is a new class URIBuilder, which provides convenient way for generating URIs.
You can use either create URI directly from String URL:
List<NameValuePair> listOfParameters = ...;URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue") .addParameter("firstParam", firstVal) .addParameter("secondParam", secondVal) .addParameters(listOfParameters) .build();
Otherwise, you can specify all parameters explicitly:
URI uri = new URIBuilder() .setScheme("http") .setHost("example.com") .setPort(8080) .setPath("/path/to/resource") .addParameter("mandatoryParam", "someValue") .addParameter("firstParam", firstVal) .addParameter("secondParam", secondVal) .addParameters(listOfParameters) .build();
Once you have created URI
object, then you just simply need to create HttpGet
object and perform it:
//create GET requestHttpGet httpGet = new HttpGet(uri);//perform requesthttpClient.execute(httpGet ...//additional parameters, handle response etc.