SORU
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ş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Charles Renaud

    Charles Rena

    10 Kasım 2007
  • Manuel Vizcaino

    Manuel Vizca

    27 Mayıs 2008
  • RyanXLT

    RyanXLT

    22 Ocak 2011