Android:java.net.HttpURLConnection - IOException是否表示无法连接到互联网或其他东西?

时间:2015-01-21 22:33:48

标签: java android httpurlconnection

我想这可能会成为同行评审请求的两倍。鉴于以下内容:

// This file is protected under the KILLGPL.
// For more information, visit http://www.lukeleber.github.io/KILLGPL.html
//
// Copyright (c) Luke Leber <LukeLeber@gmail.com>

package com.lukeleber.util.network;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Looper;
import android.util.Log;

import com.lukeleber.util.BuildConfig;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@SuppressWarnings("unused")
public final class Connectivity
{
    /// @internal debugging tag
    private final static String TAG = Connectivity.class.getName();

    /// The default URL for tests that connect to the internet
    public final static String DEFAULT_INTERNET_TEST_URL = "http://www.google.com";

    /// The default time-out for tests that connect to the internet
    public final static int DEFAULT_INTERNET_TIMEOUT_MILLIS = 1000;

    /// Uninstantiable
    private Connectivity()
    {

    }

    public static boolean isConnectedToInternet(final Context context, final String testURL,
                                                final int timeoutMillis)
    {
        /// Debugging check only - provides a slightly stricter policy than the android runtime,
        /// as this check catches 100% of the erroneous calls to this method whereas the built-in
        /// routine will only catch calls that actually make it to the blocking HTTP connection.
        /// As this check is omitted from release builds, we can only hope that the sources were
        /// at least compiled and ran in debug mode prior to shipping.
        if(BuildConfig.DEBUG && Looper.myLooper().equals(Looper.getMainLooper()))
        {
            Log.e(TAG, "blocking method called on UI thread");
        }
        if(context == null)
        {
            if(BuildConfig.DEBUG)
            {
                Log.w(TAG, "Null value for 'context'");
            }
            throw new IllegalArgumentException("context == null");
        }
        if(testURL == null)
        {
            if(BuildConfig.DEBUG)
            {
                Log.w(TAG, "Null value for 'testURL'");
            }
            throw new IllegalArgumentException("testURL == null");
        }
        if(timeoutMillis < 0)
        {
            if(BuildConfig.DEBUG)
            {
                Log.w(TAG, "Illegal value for 'timeoutMillis': " + timeoutMillis);
            }
            throw new IllegalArgumentException("timeoutMillis < 0");
        }
        final String[] requiredPermissions = new String[]
        {
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET
        };
        final PackageManager pm = context.getPackageManager();
        final String packageName = context.getPackageName();
        for(final String permission : requiredPermissions)
        {
            if(PackageManager.PERMISSION_GRANTED != pm.checkPermission(permission, packageName))
            {
                Log.w(TAG, "Unable to check internet connectivity: Permission " +
                        permission + " is not granted.");
                return false;
            }
        }
        final ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if(cm == null)
        {
            return false;
        }
        final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected())
        {
            HttpURLConnection connection = null;
            try
            {
                connection = (HttpURLConnection)new URL(testURL).openConnection();
                    connection.setConnectTimeout(1);
                connection.connect();
                return connection.getResponseCode() == Constants.HTTP.HTTP_RESPONSE_OK;
            }
            catch(final MalformedURLException murle)
            {
                if(BuildConfig.DEBUG)
                {
                    Log.w(TAG, "testURL is an invalid URL", murle);
                }
                throw (IllegalArgumentException)
                        new IllegalArgumentException("testURL is not a valid URL")
                                .initCause(murle);
            }
            catch (final IOException e)
            {
                /// todo: research why this might happen
                /// Maintainer,
                /// Is it better to return false (assume the internet is unreachable)
                /// or to throw an exception (we don't know if the internet is reachable)?
                if(BuildConfig.DEBUG)
                {
                    Log.w(TAG, "Unknown error", e);
                }
            }
            finally
            {
                if(connection != null)
                {
                    connection.disconnect();
                }
            }
        }
        return false;
    }

100%的IOException是否表示连接失败 - 或者JDK文档是否记录了任何细微之处?

此代码有三个结果:

1)返回true - 应用程序具有互联网连接
2)返回false - 应用程序没有互联网连接
3)抛出异常 - 某些东西是不对的,因此结果可能是真的也可能是假的。

每个人都在想什么?

0 个答案:

没有答案