Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:java.net.HttpURLConnection-IOException是否表示无法连接到internet或其他东西?_Java_Android_Httpurlconnection - Fatal编程技术网

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

Android:java.net.HttpURLConnection-IOException是否表示无法连接到internet或其他东西?,java,android,httpurlconnection,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 and

我想这可以作为同行评审的要求。鉴于以下情况:

// 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;
    }
IOException 100%是否表示连接失败?或者是否存在JDK文档未记录的任何细节

此代码有三个结果:

1返回true-应用程序具有internet连接 2返回false-应用程序没有internet连接 3抛出异常-某些内容不正确,因此结果可能为真或假


每个人都怎么想?

IOException是大量异常的根源。从协议到中断的i/o、所有与ssl相关的错误、可能发生在与internet断开连接的网络上的未知主机或没有到主机的路由、超时等等。。。更重要的是,在出现这种异常的情况下,是否可以安全地假设连接故障是最终原因?或者灾难性的本地故障。@LukeA.Leber显然不是。您能提供一个其他示例吗?一个典型的错误案例是,在仍然具有正确连接的情况下,由于设备上设置了错误的日期而导致SSL异常。