检查网站是否在线

时间:2014-03-05 13:44:08

标签: java android

我正在尝试检查website是否在线。我已经尝试过了:

    public static boolean checkisonline(String targetUrl) {

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

    HttpURLConnection httpUrlConn;
    try {
        httpUrlConn = (HttpURLConnection) new URL(targetUrl)
                .openConnection();

        httpUrlConn.setRequestMethod("HEAD");

        // Set timeouts in milliseconds
        httpUrlConn.setConnectTimeout(30000);
        httpUrlConn.setReadTimeout(30000);

        // Print HTTP status code/message for your information.
        System.out.println("Response Code: "
                + httpUrlConn.getResponseCode());
        System.out.println("Response Message: "
                + httpUrlConn.getResponseMessage());

        return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
        return false;
    }
}

但即使网站在线,我总是在输出中得到Error: null

Stackdrace:
03-05 14:51:30.931 8409-8460/de.treevo.app I/System.out﹕ Error: null 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ java.io.EOFException 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at java.util.zip.GZIPInputStream.readFully(GZIPInputStream.java:202) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:98) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:468) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:666) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503) 03-05 14:51:30.931 8409-8460/de.treevo.app W/System.err﹕ at de.treevo.core.functions.checkisonline(functions.java:79) 03-05 14:51:30.941 8409-8460/de.treevo.app W/System.err﹕ at de.treevo.app.add_series$1.run(add_series.java:167) 03-05 14:51:30.941 8409-8460/de.treevo.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)

1 个答案:

答案 0 :(得分:2)