DefaultHttpClient to AndroidHttpClient

Use an AsyncTask so that the network request does not block the UI thread. The NetworkOnMainThreadException was introduced since API version 11, which is the reason why it is only showing up 3.0 and up.

private class NetworkTask extends AsyncTask<String, Void, HttpResponse> {
    @Override
    protected HttpResponse doInBackground(String... params) {
        String link = params[0];
        HttpGet request = new HttpGet(link);
        AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        try {
            return client.execute(request);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
        client.close();
    }
    }

    @Override
    protected void onPostExecute(HttpResponse result) {
        //Do something with result
        if (result != null)
            result.getEntity().writeTo(new FileOutputStream(f));
    }
}

To call this thread simple do this.

new NetworkTask().execute(linkk);

Take a look at this article written on the Android developer site. It explains in more detail how to write your app to handle threads.


StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation (include HttpClient and HttpUrlConnection) get executed on UI thread. if you do this, you get NetworkOnMainThreadException.

This restriction can be changed, using:

    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

Add the above code into your main activity's onCreate() method.

In addition, it is always recommended to move network operation off the UI thread, for example, using AsyncTask.

hope this help.