Come utilizzare DefaultHttpClient su Android?[Chiuso]
Domanda
Come utilizzare DefaultHttpClient in Android?
Soluzione
Suggerisco di leggere i tutorial forniti con android-api.
Ecco un esempio casuale che utilizza DefaultHttpClient, trovato tramite una semplice ricerca di testo nella cartella degli esempi.
EDIT: il sample-source non aveva lo scopo di mostrare qualcosa.Ha solo richiesto il contenuto dell'URL e lo ha memorizzato come stringa.Ecco un esempio che mostra cosa è stato caricato (purché si tratti di dati stringa, come un file 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"
/>
in onCreate della tua app aggiungi:
// 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());
}
Questo esempio ora carica il contenuto dell'URL specificato (OpenSearchDescription per stackoverflow nell'esempio) e scrive i dati ricevuti in un TextView.
Altri suggerimenti
Ecco un esempio di codice generale:
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 ....
public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)
Crea un nuovo client HTTP da parametri e un gestore di connessione.
Parametri
"conman"
il gestore della connessione,
"params"
i parametri
public DefaultHttpClient (HttpParams params)
public DefaultHttpClient ()