still under construction, but feel free to explore :)
HOME / Articles/Tutorials / Android Articles/Tutorials / Tutorials on Android programming / Tutorials on Web and Web Services / Android HTTP tutorial

Android HTTP tutorial

Guide and examples about Http connections, requests/replies in Android




This artcile is based on Android 4.3 API 18

1. Introduction to Main Http Classes in Android

1.1 Apache HttpClient

The Apache HttpClient class has been used for many apps in the past it has to implementation:

1.2 Android’s HttpURLConnection

Android's HttpURLConnection is a standard Java lightweight HTTP client it is a is a general-purpose implementation suitable for most apps.

2. Which is better.

HttpURLConnection and Apache HttpClient both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling.

Apache http clients are big and flexible implementations, however exactly because of their complexity they are not actively supported by Android team.

HttpURLConnection on the other hand is smaller and lighter and can serve the needs of most apps. It is also continuously improved by the Android team.

Finally as noted in the API docs:
For Android 2.3 (Gingerbread) and later, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery.

3. Examples

To access the web we need to enable android.permission.INTERNET in the AndroidManifest.xml.
		    
		    

In Android applications file and network operation should be done on a separate a thread in order to avoid ANR. As of Android 3 (API11) using network access on the main(UI) thread will cause StrictMode to throw NetworkOnMainThreadException. For simlicity in this exmple we use network access on the main thread using the following code.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*
         * this is to allow network operations in the main thread
         * it is done for code simplicity for this example
         * DO NOT DO THIS in real apps
        */
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 
    }
		        

In the following 2 example we use common method to read the data from an InputStream :
    private StringBuilder readStream(InputStream in) {
        StringBuilder res = new StringBuilder();  
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = br.readLine()) != null) {
                res.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    } 		           
		           
		       

The following 2 exmples access a simple web page and displays its content. The argument request is the url address.

3.1 Using Appache HttpClient

    private String useApacheHttpClient(String request) {
        String result = "";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(request);
             HttpResponse response = httpClient.execute(httpGet);
             result =  readStream(response.getEntity().getContent()).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }				        
				    

3.2 Using HttpURLConnection

    private String useHttpURLConnection(String request) {
        String result = "";
        try {
            URL url = new URL(request);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            result = readStream(con.getInputStream()).toString();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }                        
                    

4. Download Examples

HttpExample.zip size: 1268046

Author: DjoDjo