Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.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
Java 如何正确处理网络状态和HTTP状态代码_Java_Android_Http_Http Status Codes - Fatal编程技术网

Java 如何正确处理网络状态和HTTP状态代码

Java 如何正确处理网络状态和HTTP状态代码,java,android,http,http-status-codes,Java,Android,Http,Http Status Codes,在一个方法中,我使用HttpURLConnection发送GET和POST请求。正如您在示例代码中看到的,我捕获了大多数异常。但我想知道这是否是正确的方法,我实际上应该如何处理服务器响应中的“无网络可用”和错误状态代码等情况?我这样问是因为我想告诉用户各种问题 public static Bitmap getImage(String url) { HttpURLConnection conn = null; try { URL newUrl = new URL(

在一个方法中,我使用HttpURLConnection发送GET和POST请求。正如您在示例代码中看到的,我捕获了大多数异常。但我想知道这是否是正确的方法,我实际上应该如何处理服务器响应中的“无网络可用”和错误状态代码等情况?我这样问是因为我想告诉用户各种问题

public static Bitmap getImage(String url) {
    HttpURLConnection conn = null;
    try {

        URL newUrl = new URL(url);

        conn = (HttpURLConnection) newUrl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("Content-Type", "image/png");
        conn.setRequestMethod("GET");

        conn.connect();

        int total = conn.getContentLength();

        InputStream is = conn.getInputStream();
        // ... read the image here!
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (conn != null)
            conn.disconnect();

        if (progress != null)
            progress.setProgress(1f);
    }
}

尝试下面的代码,并根据您的要求在下面的课程中添加:-

catch (Exception e)
        {
            e.printStackTrace();
            publishProgress(ExceptionHandling.getFormattedMessageFromException(e.getMessage()));
        }
异常处理.java

public class ExceptionHandling
{
    public static String exception= "No address associated with hostname";
    public static String exceptionReturn = "No Internet Connection";
    public static String exceptionTimeOut = "ETIMEDOUT";
    public static String exceptionTimeoutReturn = "Connection time out, try again";
    public static String exceptionConnectionRefused = "Connection to http://54.254.213.212 refused";
    public static String exceptionConRefusedReturn = "Connection lost, please try again...";
    public static String exceptionEconnReset = "ECONNRESET";
    public static String exceptionSOCKET = "SocketTimeoutException";

    public static String exceptionTimeOuturl ="Connect to /154.25.13.12:80 timed out";
    public static String exceptionTimeOuturl1 ="ap-southeast-1.compute.amazonaws.com/154.25.13.12:80  timed out";
    public static String exceptionTimeOuturlreturn2 ="time out";
    public static String exceptionTimeOuturlreturn3 ="refused";


    public static String exceptionTimeOuturlreturn ="Connection time out, try again";
    public static String exceptionEConnResetReturn = "Trying to connect ... ";

    public static String returnVal = "Server connection failed. Please try again.";

    public static String getFormattedMessageFromException(String exceptionMessage)
    {
        try
        {
//          return returnVal;exceptionSOCKET
            if(exceptionMessage.contains(exceptionSOCKET))
            {
                return exceptionTimeoutReturn;
            }
            if(exceptionMessage.contains(exception))
            {
                return exceptionReturn;
            }
            if(exceptionMessage.contains(exceptionTimeOut))
            {
                return exceptionTimeoutReturn;
            }
            if(exceptionMessage.contains(exceptionConnectionRefused))
            {
                return exceptionConRefusedReturn;
            }
            if(exceptionMessage.contains(exceptionEconnReset))
            {
                return exceptionEConnResetReturn;
            }
            if(exceptionMessage.contains(exceptionTimeOuturl))
            {
                return exceptionTimeOuturlreturn;
            }
            if(exceptionMessage.contains(exceptionTimeOuturl1))
            {
                return exceptionTimeOuturlreturn;
            }
            if(exceptionMessage.contains(exceptionTimeOuturlreturn2))
            {
                return exceptionTimeOuturlreturn;
            }
            if(exceptionMessage.contains(exceptionTimeOuturlreturn3))
            {
                return exceptionConRefusedReturn;
            }
            else
            {
                return exceptionConRefusedReturn; 
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return exceptionMessage;
    }

}

添加更多消息。

使用此选项检查网络是否可用

    ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()
                    && conMgr.getActiveNetworkInfo().isConnected()) {
                //connection aailable
            }else{
//no connection
}
如果连接可用,您可以发出http请求&如果以后出现任何连接错误
然后exception.getMessage()给出了正确的错误消息,可以显示给用户

良好的起点。但是大多数错误案例都可以通过使用而不是字符串比较来发现,对吗?这是一个糟糕的起点。这是一个邪恶的混乱,它依赖于各种异常消息的未记录属性,而忽略了正确的方法,即分别捕获它们。我想您只需要显示与网络错误相关的用户消息,如超时、网关超时、找不到数据。因此,只需捕获响应代码并显示该代码的描述。这只是其中的一部分。您还需要检查HTTP状态代码或连接超时。