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

时间:2014-04-22 07:24:27

标签: java android http http-status-codes

在方法中,我使用HttpURLConnection发送GET和POST请求。正如您在示例代码中看到的,我抓住了大多数异常。但是我想知道这是否是正确的方法,以及我如何处理像#34;没有可用的网络和#34;和来自服务器的响应中的错误状态代码?我问这个是因为我想告诉用户各种问题。

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);
    }
}

2 个答案:

答案 0 :(得分:0)

用它来检查网络是否可用

    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()提供可以显示给用户的正确错误消息

答案 1 :(得分:-1)

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

catch (Exception e)
        {
            e.printStackTrace();
            publishProgress(ExceptionHandling.getFormattedMessageFromException(e.getMessage()));
        }

<强> ExceptionHandling.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;
    }

}

添加更多消息。

相关问题