pragmatic
pragmatic

Reputation: 95

Android: Getting HTTP status codes using DefaultHttpClient

I'm a newbie in android development. I'm trying to write a small app that prints the HTTP status code of the queried URL.

For any valid URL query, I'm getting 200 (as expected). but when I query a non-existent URL I get 0 (instead of a HTTP error code). This is what I can see from logcat-

System.err java.net.UnknownHostException: Unable to resolve host "www.adsxgp.com": No address associated with hostname

What am I missing here?

This is my code-

public class MainActivity extends Activity {

    private static String logtag = "TwoButtonApp";//for use as the tag when logging 
    private TextView textView;  
     /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            textView = (TextView)findViewById(R.id.TextBox01);

        }

        private class CloudLookup extends AsyncTask<String, Void, String>{
                @Override
                protected String doInBackground(String... urls) {
                // TODO Auto-generated method stub

                int responseCode = 0;
                for (String url : urls){
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);


                    try {

                        HttpResponse execute = client.execute(httpGet);
                        responseCode = execute.getStatusLine().getStatusCode();

                        /*
                        URL obj = new URL(urls[0]);
                        con = (HttpURLConnection)obj.openConnection();
                        con.setRequestMethod("GET");
                        String USER_AGENT= "Mozilla/5.0";
                        con.setRequestProperty("User-Agent", USER_AGENT);

                        responseCode = con.getResponseCode(); */

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                    return Integer.toString(responseCode);

                }


            @Override
            protected void onPostExecute(String result){
                Toast.makeText(MainActivity.this, "Yo! I was called!" +result, Toast.LENGTH_LONG).show();
            }
        }



        public void onClick(View view) {
            CloudLookup cl = new CloudLookup();
            cl.execute(new String[]{"http://www.adsxgp.com"});
            Log.d(logtag,"onClick() called");

        }


        @Override
     protected void onStart() {//activity is started and visible to the user
      Log.d(logtag,"onStart() called");
      super.onStart();  
     }
     @Override
     protected void onResume() {//activity was resumed and is visible again
      Log.d(logtag,"onResume() called");
      super.onResume();

     }
     @Override
     protected void onPause() { //device goes to sleep or another activity appears
      Log.d(logtag,"onPause() called");//another activity is currently running (or user has pressed Home)
      super.onPause();

     }
     @Override
     protected void onStop() { //the activity is not visible anymore
      Log.d(logtag,"onStop() called");
      super.onStop();

     }
     @Override
     protected void onDestroy() {//android has killed this activity
       Log.d(logtag,"onDestroy() called");
       super.onDestroy();
     }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Upvotes: 0

Views: 835

Answers (2)

FrAn
FrAn

Reputation: 434

The failure is confined with the underlying API's ability to resolve the hostname. So basically you are passing "www.adsxgp.com" as the URL to load the DNS server can't map IP address to it because it doesn't exist so you get nothing, so the HTTP request will fail.

Upvotes: 1

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

There is no actual response from the server (since you weren't able to connect to one), hence no valid HTTP status code (0 is not a valid HTTP response code). The status code was simply never set in this case, and so has the default value for an int.

The real problem is that you are suppressing the Exception (just logging it, but continuing operation as if it never happened). The exception means that you did not successfully communicate with the server, and so your responseCode is meaningless.

Upvotes: 1

Related Questions