How to use DefaultHttpClient in Android?
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.
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 ....
From Google Documentation
public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)
Creates a new HTTP client from parameters and a connection manager.
Parameters
"conman"
the connection manager,
"params"
the parameters
public DefaultHttpClient (HttpParams params)
public DefaultHttpClient ()
© 2022 - 2024 — McMap. All rights reserved.