Make an HTTP request with android

First of all, request a permission to access network, add following to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

If you want make an HTTP request, We had recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    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();
                responseString = out.toString();
            } else{
                //Closes the connection.
                throw new IOException(statusLine.getReasonPhrase());
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        return responseString;

    protected void onPostExecute(String result) {
        //Do anything with response..

Now in your Activity you must make call resquest in onCreate:

new RequestTask().execute("");

Download code

Leave a Reply

Your email address will not be published. Required fields are marked *