Pregunta

Cómo utilizar DefaultHttpClient en Android?

¿Fue útil?

Solución

Sugiero leer los tutoriales proporcionados con android-api.

Aquí hay un ejemplo aleatorio que usa DefaultHttpClient, que se encuentra mediante una simple búsqueda de texto en la carpeta examples.

EDITAR: La fuente de muestra no tenía la intención de mostrar algo.Simplemente solicitó el contenido de la URL y lo almacenó como cadena.Aquí hay un ejemplo que muestra lo que cargó (siempre que sea una cadena de datos, como un archivo html, css o javascript):

<×main.xml

  <?xml version="1.0" encoding="utf-8"?>
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/textview"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
  />

en onCreate de su aplicación agregue:

  // Create client and set our specific user-agent string
  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet("http://stackoverflow.com/opensearch.xml");
  request.setHeader("User-Agent", "set your desired User-Agent");

  try {
      HttpResponse response = client.execute(request);

      // Check if server response is valid
      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() != 200) {
          throw new IOException("Invalid response from server: " + status.toString());
      }

      // Pull content stream from response
      HttpEntity entity = response.getEntity();
      InputStream inputStream = entity.getContent();

      ByteArrayOutputStream content = new ByteArrayOutputStream();

      // Read response into a buffered stream
      int readBytes = 0;
      byte[] sBuffer = new byte[512];
      while ((readBytes = inputStream.read(sBuffer)) != -1) {
          content.write(sBuffer, 0, readBytes);
      }

      // Return result from buffered stream
      String dataAsString = new String(content.toByteArray());

      TextView tv;
      tv = (TextView) findViewById(R.id.textview);
      tv.setText(dataAsString);

  } catch (IOException e) {
     Log.d("error", e.getLocalizedMessage());
  }

Este ejemplo ahora carga el contenido de la URL dada (OpenSearchDescription para stackoverflow en el ejemplo) y escribe los datos recibidos en un TextView.

Otros consejos

Aquí hay un ejemplo de código general:

DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

HttpGet method = new HttpGet(new URI("http://foo.com"));
HttpResponse response = defaultHttpClient.execute(method);
InputStream data = response.getEntity().getContent();
//Now we use the input stream remember to close it ....

De Documentación De Google

public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)

Crea un nuevo cliente HTTP de parámetros y un administrador de conexión.

Parámetros
"conman" el administrador de conexión,
"params" los parámetros

public DefaultHttpClient (HttpParams params)
public DefaultHttpClient ()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top