Android:使用DefaultHttpClient获取HTTP状态代码

时间:2015-01-27 20:32:34

标签: android http

我是Android开发的新手。我正在尝试编写一个打印查询URL的HTTP状态代码的小应用程序。

对于任何有效的网址查询,我得到200(正如预期的那样)。但是当我查询不存在的URL时,我得到0(而不是HTTP错误代码)。这是我从logcat中看到的 -

  

System.err java.net.UnknownHostException:无法解析主机   " www.adsxgp.com":没有与主机名相关联的地址

我在这里缺少什么?

这是我的代码 -

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);
    }
}

2 个答案:

答案 0 :(得分:1)

服务器没有实际响应(因为您无法连接到一个),因此没有有效的HTTP状态代码(0不是有效的HTTP响应代码)。在这种情况下,状态代码根本就没有设置,因此具有int的默认值。

真正的问题是你正在抑制异常(只是记录它,但继续操作就像从未发生过一样)。该异常意味着您未成功与服务器通信,因此您的responseCode毫无意义。

答案 1 :(得分:1)

失败仅限于底层API解析主机名的能力。所以基本上你正在通过&#34; www.adsxgp.com&#34;因为加载DNS服务器的URL无法将IP地址映射到它,因为它不存在所以你什么也得不到,所以HTTP请求将失败。