How to use DefaultHttpClient in Android?

Umer Hassam picture Umer Hassam · Mar 23, 2011 · Viewed 28.2k times · Source

How to use DefaultHttpClient in Android?

Answer

MacGucky picture MacGucky · Mar 23, 2011

I suggest reading the tutorials provided with android-api.

Here is some random example which uses DefaultHttpClient, found by simple text-search in examples-folder.

EDIT: The sample-source was not intended to show something. It just requested the content of the url and stored it as string. Here is an example which shows what it loaded (as long as it is string-data, like an html-, css- or javascript-file):

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"
  />

in onCreate of your app add:

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

This example now loads the content of the given url (the OpenSearchDescription for stackoverflow in the example) and writes the received data in an TextView.