[java] How to add parameters to a HTTP GET request in Android?

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.

This question is related to java android http-get

The answer is


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

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


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.

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


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

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.


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to http-get

How do I print the content of httprequest request? PHP cURL GET request and request's body How to pass complex object to ASP.NET WebApi GET from jQuery ajax call? Cache an HTTP 'Get' service response in AngularJS? How to use HTTP GET in PowerShell? How can I pass POST parameters in a URL? Writing image to local server OS X: equivalent of Linux's wget How to add parameters to a HTTP GET request in Android? Are querystring parameters secure in HTTPS (HTTP + SSL)?