groomsy groomsy - 4 months ago 30
Java Question

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.

Answer

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