java – 对某些异常重新尝试方法
发布时间:2020-12-15 02:15:29  所属栏目:Java  来源:网络整理 
            导读:我有以下方法使用代理从服务器检索信息.有时由于代理错误,我得到SocketException,SSLException,SSLHandshakeException或ConnectException 正如你在我的方法中看到的,我已经在使用catch(IOException ioe)我需要这样做,以便在服务器返回除代码200之外的任何内
                
                
                
            | 
                         
 我有以下方法使用代理从服务器检索信息.有时由于代理错误,我得到SocketException,SSLException,SSLHandshakeException或ConnectException 
  
  
正如你在我的方法中看到的,我已经在使用catch(IOException ioe)我需要这样做,以便在服务器返回除代码200之外的任何内容时获取服务器响应的内容. 如果出现上述异常,如何重置方法? public String getMeta() throws IOException
{
    HttpsURLConnection con = null;
    InputStream is = null;
    StringWriter writer = new StringWriter();
    try
    {
        String url = "https://api.myapp.com/meta";
        URL urlObj = new URL(url);
        if (useProxy && fullProxy)
        {
            myapp.Proxy proxyCustom = getRandomProxy();
            Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyCustom.getProxyIp(),proxyCustom.getProxyPort()));
            con = (HttpsURLConnection) urlObj.openConnection(proxy);
        }
        else
        {
            con = (HttpsURLConnection) urlObj.openConnection();
        }
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent",USER_AGENT);
        con.setRequestProperty("Content-Type","application/json; charset=utf-8");
        con.setRequestProperty("host",urlObj.getHost());
        con.setRequestProperty("Connection","Keep-Alive");
        int responseCode = 0;
        responseCode = con.getResponseCode();
        is = con.getInputStream();
        writer = new StringWriter();
        IOUtils.copy(is,writer,"UTF-8");
    }
    catch (IOException ioe)
    {
        if (con instanceof HttpsURLConnection)
        {
            HttpsURLConnection httpConn = (HttpsURLConnection) con;
            int statusCode = httpConn.getResponseCode();
            if (statusCode != 200)
            {
                is = httpConn.getErrorStream();
                writer = new StringWriter();
                IOUtils.copy(is,"UTF-8");
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return writer.toString();
}
解决方法
 下面显示的一种方法是让getMeta方法实际抛出IOException.然后,由于任何捕获的异常,您可以使用调用方法递归调用自身. 
 为了能够多次调用该方法,传递次数作为参数并相应地处理停止标准逻辑.例如: public String caller(int total) throws IOException{
    return callerImpl(1,total);
}
public String callerImpl(int current,int total) throws IOException{
    try{
        return getMeta();
    }catch(IOException e){
        current++;
        if ( current > total ){
            throw e;//or return null or empty string,depending upon upstream requirements
        }
        return callerImpl(current,total);
    }
    return null;
} 
 在getMeta中: try{
    ....
}catch(IOException io){
    //log or handle io
    throw io;
} 
 注意,上面没有涉及抛出异常的日志/逻辑,您可能希望以某种方式处理它们. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
