How to use DefaultHttpClient in Android?

How to use DefaultHttpClient in Android?

+7
source share
3 answers

I suggest reading tutorials provided using android-api.

Here are a few random examples that use DefaultHttpClient found by a simple text search in the examples folder.

EDIT: The sample source is not intended to show something. He simply requested the contents of the URL and saved it as a string. Here is an example that shows what it uploaded (so far this is string data such as 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 application 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 downloads the contents of this URL (OpenSearchDescription for stackoverflow in the example) and writes the resulting data to a TextView.

+15
source

Here is an example of common code:

 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 .... 
+3
source

From Google Documentation

public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)

Creates a new HTTP client from the settings and connection manager.

Options
"conman" connection manager,
"params" parameters

 public DefaultHttpClient (HttpParams params) public DefaultHttpClient () 
0
source

All Articles