pihu
pihu

Reputation: 93

Unable to resolve host for http connection

I am trying out a simple http connection through this program but getting resourcenotfoundexception, Unable to resolve host "www.google.com": No address associated with hostname.What is the reason behind this ?

public class HttpClientActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

//      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
//              .permitAll().build();
//      StrictMode.setThreadPolicy(policy);

//      connect();

        new Connection().execute();

    }

    private class Connection extends AsyncTask {

        @Override
        protected Object doInBackground(Object... arg0) {
            connect();
            return null;
        }

    }

    private void connect() {
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet("http://www.google.com");
            HttpResponse response = client.execute(request);
        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }
    }

}

Upvotes: 1

Views: 1678

Answers (1)

MDMalik
MDMalik

Reputation: 4001

Please verify that you are allowed to access the internet from your APP.

The permission for that is defined in AndroidManifest.xml. Make sure you have the below permission

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

EDIT If still not working try this code

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000);
urlc.connect();
Log.i(Tag,Integer.toString(urlc.getResponseCode()));

Upvotes: 2

Related Questions