17 AĞUSTOS 2010, Salı
Android ile bir HTTP isteği yapmak
Her yeri aradım ama cevabımı bulamadım, basit bir HTTP isteği yapmak için bir yolu var mı? Web siteme bir script / PHP sayfasına istek yapmak istiyorum ama web sayfasında göstermek istemiyorum.
Mümkünse ben bile arka planı (BroadcastReceiver) yapmak istiyor
CEVAP
17 AĞUSTOS 2010, Salı
Öncelikle bildirim için aşağıdaki ağ erişimi, eklemek için izin istiyorum:
<uses-permission android:name="android.permission.INTERNET" />
O zaman en kolay yolu Apache http client Android ile birlikte kullanmak için:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
Eğer bu ayrı bir iş parçacığı üzerinde çalıştırmak istiyorsanız AsyncTask uzanan öneriyorum:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
Eğer bir istek yapabilirsiniz:
new RequestTask().execute("http://stackoverflow.com");
Bunu Paylaş:
Nasıl bir HTTP GET isteği Ruby on Rail...
Nasıl C ile HTTP isteği yapmak mı ?...
Ne kadar Hızlı bir HTTP isteği yapmak ...
Nasıl bir http isteği Android çerezler...
Nasıl android HTTP kimlik doğrulaması ...