How to check internet access on Android? InetAddress never times out

后端 未结 30 3344
猫巷女王i
猫巷女王i 2020-11-21 04:45

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

30条回答
  •  盖世英雄少女心
    2020-11-21 04:46

    It's works for me. Try it out.

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            URL url = new URL("http://stackoverflow.com/posts/11642475/edit" );
            //URL url = new URL("http://www.nofoundwebsite.com/" );
            executeReq(url);
            Toast.makeText(getApplicationContext(), "Webpage is available!", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e) {
            Toast.makeText(getApplicationContext(), "oops! webpage is not available!", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void executeReq(URL urlObject) throws IOException
    {
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) urlObject.openConnection();
        conn.setReadTimeout(30000);//milliseconds
        conn.setConnectTimeout(3500);//milliseconds
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
    
        // Start connect
        conn.connect();
        InputStream response =conn.getInputStream();
        Log.d("Response:", response.toString());
    }}
    

提交回复
热议问题