122

I have a HTTP GET request that I am attempting to send. I tried adding the parameters to this request by first creating a BasicHttpParams object and adding the parameters to that object, then calling setParams( basicHttpParms ) on my HttpGet object. This method fails. But if I manually add my parameters to my URL (i.e. append ?param1=value1&param2=value2) it succeeds.

I know I'm missing something here and any help would be greatly appreciated.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
groomsy
  • 4,945
  • 6
  • 29
  • 33
  • 1
    For a GET request, the second method is the correct way to add parameters. I expect the first approach is for POST methods. – James Black Jun 02 '10 at 15:56

7 Answers7

226

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;
}
Brian Griffey
  • 4,751
  • 1
  • 25
  • 26
  • I agree. I've gone back and changed this as this method makes sense for larger amounts of parameters. The first accepted answer still works fine, but can be confusing for large sets of parameters. – groomsy Jul 11 '11 at 13:55
  • @Brian Griffey Thanks for good Solution. but i have little different format to pass parameter, Can anyone help me to pass this parameter..? How to pass parameter in this case? data = '{ "credential": { "accesToken": "668f514678c7e7f5e71a07044935d94c", "ACK": "cf3bb509623a8e8fc032a08098d9f7b3" }, "restIn": { "userId": 4, "listId": 5613 } } ; – Yog Guru Sep 21 '12 at 12:38
  • 1
    The other answer is much shorter and simpler for simple cases. It's not wrong, and worth considering. – qris Dec 05 '12 at 23:17
  • 2
    List is deprecated in android api level 22 – Vihaan Verma Apr 21 '15 at 12:05
  • @SimonMeier : use Uri.Builder() . See the answer below. – Vihaan Verma Jul 03 '15 at 13:03
  • Not that it matters much, but why a LinkedList? – Gerard Aug 01 '15 at 23:40
  • Please use Retrofit instead of manually building URL schemes. – Brian Griffey Jan 12 '16 at 19:58
99

To build uri with get parameters, Uri.Builder provides a more effective way.

Uri uri = new Uri.Builder()
    .scheme("http")
    .authority("foo.com")
    .path("someservlet")
    .appendQueryParameter("param1", foo)
    .appendQueryParameter("param2", bar)
    .build();
Flimm
  • 136,138
  • 45
  • 251
  • 267
9re
  • 2,408
  • 27
  • 27
  • Also cant handle file parameters – siamii Jul 31 '11 at 04:40
  • @bizso09 "file parameters" do you mean query and fragment? They are both settable by the builder. Have a look at this for URI terminology, it helped me a lot http://developer.android.com/reference/java/net/URI.html – dvd Jan 24 '13 at 22:16
  • how to remove query parameter? how to change value of existing query parameter? – Piotr Feb 15 '14 at 02:24
  • there's a clear method http://developer.android.com/reference/android/net/Uri.Builder.html#clearQuery(). to modify, assume that you have a list of queries, update the value in the list, clearQuery() and then call appendQueryParameter in the loop of the list. but why not create the new one every time on demand? – 9re Feb 15 '14 at 10:26
31

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 request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
n1ckolas
  • 4,380
  • 3
  • 37
  • 43
29

The method

setParams() 

like

httpget.getParams().setParameter("http.socket.timeout", new Integer(5000));

only adds HttpProtocol parameters.

To execute the httpGet you should append your parameters to the url manually

HttpGet myGet = new HttpGet("http://foo.com/someservlet?param1=foo&param2=bar");

or use the post request the difference between get and post requests are explained here, if you are interested

skaffman
  • 398,947
  • 96
  • 818
  • 769
n3utrino
  • 2,361
  • 3
  • 22
  • 32
  • 1
    Thank you for your help. I thought there might be a more effective way of adding parameters to GET requests. – groomsy Jun 02 '10 at 16:29
8
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1","value1");

String query = URLEncodedUtils.format(params, "utf-8");

URI url = URIUtils.createURI(scheme, userInfo, authority, port, path, query, fragment); //can be null
HttpGet httpGet = new HttpGet(url);

URI javadoc

Note: url = new URI(...) is buggy

siamii
  • 23,374
  • 28
  • 93
  • 143
6
    HttpClient client = new DefaultHttpClient();

    Uri.Builder builder = Uri.parse(url).buildUpon();

    for (String name : params.keySet()) {
        builder.appendQueryParameter(name, params.get(name).toString());
    }

    url = builder.build().toString();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity(), "UTF-8");
Yorty Ruiz
  • 81
  • 1
  • 1
0

If you have constant URL I recommend use simplified http-request built on apache http.

You can build your client as following:

private filan static HttpRequest<YourResponseType> httpRequest = 
                   HttpRequestBuilder.createGet(yourUri,YourResponseType)
                   .build();

public void send(){
    ResponseHendler<YourResponseType> rh = 
         httpRequest.execute(param1, value1, param2, value2);

    handler.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
     rh.ifHasContent(content -> // your code);
}

public void whenSuccess(ResponseHendler<YourResponseType> rh){
   LOGGER.error("Status code: " + rh.getStatusCode() + ", Error msg: " + rh.getErrorText());
}

Note: There are many useful methods to manipulate your response.

Beno
  • 945
  • 11
  • 22