Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DefaultHttpClient in Android? [closed]

How to use DefaultHttpClient in Android?

like image 624
Umer Hassam Avatar asked Mar 23 '11 19:03

Umer Hassam


2 Answers

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.

like image 138
MacGucky Avatar answered Sep 21 '22 12:09

MacGucky


Here is a general code example:

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 ....
like image 44
Necronet Avatar answered Sep 20 '22 12:09

Necronet