¿Cómo agregar parámetros a una solicitud HTTP GET en Android?


Tengo una solicitud HTTP GET que estoy intentando enviar. Intenté agregar los parámetros a esta solicitud creando primero un objeto BasicHttpParams y agregando los parámetros a ese objeto, luego llamando a setParams( basicHttpParms ) en mi objeto HttpGet. Este método falla. Pero si agrego manualmente mis parámetros a mi URL (es decir, append ?param1=value1&param2=value2), tiene éxito.

Sé que me estoy perdiendo algo aquí y cualquier ayuda sería muy apreciada.

Author: Vertexwahn, 2010-06-02

8 answers

Utilizo una Lista de Namevaluuepair y URLEncodedUtils para crear la cadena de url que quiero.

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;
}
 224
Author: Brian Griffey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-12 00:15:49

Para construir uri con parámetros get, Uri.Builder proporciona una forma más efectiva.

Uri uri = new Uri.Builder()
    .scheme("http")
    .authority("foo.com")
    .path("someservlet")
    .appendQueryParameter("param1", foo)
    .appendQueryParameter("param2", bar)
    .build();
 94
Author: 9re,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 17:39:37

A partir de Componentes HTTP 4.2+ hay una nueva clase UriBuilder , que proporciona una forma conveniente para generar URI.

Puede usar crear URI directamente desde la URL de cadena:

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

De lo contrario, puede especificar todos los parámetros explícitamente:

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

Una vez que haya creado el objeto URI, simplemente debe crear el objeto HttpGet y ejecutarlo:

//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.
 30
Author: n1ckolas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 17:19:08

El método

setParams() 

Como

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

Solo agrega parámetros HttpProtocol.

Para ejecutar el HttpGet debe agregar sus parámetros a la url manualmente

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

O utilice la solicitud post la diferencia entre las solicitudes get y post se explica aquí , si está interesado

 27
Author: n3utrino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-24 18:12:37
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

Nota: url = new URI(...) es buggy

 8
Author: siamii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-30 21:42:42
    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");
 4
Author: Yorty Ruiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-27 21:44:23
 class Searchsync extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        HttpClient httpClient = new DefaultHttpClient();/*write your url in Urls.SENDMOVIE_REQUEST_URL; */
        url = Urls.SENDMOVIE_REQUEST_URL; 

        url = url + "/id:" + m;
        HttpGet httpGet = new HttpGet(url);

        try {
            // httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // httpGet.setEntity(new StringEntity(json.toString()));
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity resEntity = response.getEntity();

            if (resEntity != null) {

                String responseStr = EntityUtils.toString(resEntity).trim();

                Log.d("Response from PHP server", "Response: "
                        + responseStr);
                Intent i = new Intent(getApplicationContext(),
                        MovieFoundActivity.class);
                i.putExtra("ifoundmovie", responseStr);
                startActivity(i);

            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }//enter code here

}
 0
Author: user3678528,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-05 10:11:49

Si tiene constant URL recomiendo usar simplified http-request construido en apache http.

Puede construir su cliente de la siguiente manera:

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

Nota: Hay muchos métodos útiles para manipular su respuesta.

 0
Author: Beno Arakelyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-23 17:42:59