2016-07-06 5 views
4

프록시를 사용하여 서버에서 정보를 검색하는 다음 방법이 있습니다. 때로는 인해 당신은 내가 서버가 아무것도 반환하면 서버 응답의 내용을 얻기 위해 그렇게 할 필요가 이미 catch (IOException ioe)을 사용하고 내 방법에서 볼 수 있듯이 내가 SocketException, SSLException, SSLHandshakeException 또는 ConnectException특정 예외에서 다시 시도하십시오.

을 얻을 나쁜 프록시

위의 예외가 발생한 경우 어떻게 메소드를 다시 시도 할 수 있습니까?

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, writer, "UTF-8"); 
      } 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return writer.toString(); 
} 
+0

루프 또는 재귀를 사용하십시오. 여분의 로직을 사용하지 않고 try 블록에서부터 새로운 메소드로 모든 것을 넣으십시오. 그러면 다른 시간에 전화 할 수 있습니다. – HopefullyHelpful

+1

'메소드 재시도를 어떻게 만들 수 있습니까? '한 번 재시도 하시겠습니까? 아니면 예외가 발생하지 않을 때까지 계속 재 시도 하시겠습니까? – copeg

+0

@copeg 재 시도해야하는 시간을 설정하는 간단한 방법이 있기를 바랍니다.하지만 너무 복잡하기 때문에 한 번만 시도하면됩니다. – Arya

답변

0

내가 할 것입니다 방법은 새로운 재시도 방법을 생성하고 만 이상의 경우 호출되도록 당신 만 재 시도를 호출해야합니다 가정입니다 귀하의 getMeta() 메소드의 마지막에 호출입니다 몇 번 따라서 getMeta하지만 그 이후, 시간

예외가 당신의 getMeta() 당신이 지금하고있는대로, 캐치는 물건을 할 것입니다 던져 경우
public String getMeta() throws IOException, RetryException 
{ 

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

     return writer.toString(); 
    } 
    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, writer, "UTF-8"); 

       return writer.toString(); 
      } 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return retryGetMeta(); 
} 


private String retryGetMeta() 
{ 
    try 
    { 
     return getMeta(); 
    } 
    finally 
    { 
     //Do your stuff 
    } 
} 

public RetryException extends Exception 
{ 
    private String message = "Retries exceeded"; 

     public String getMessage() 
     { 
     return message; 
     } 

} 

의 특정 숫자 후 RetryException 같은 일부 예외를 발생한다, retryGetMeta가 호출됩니다.

+0

답변을 주셔서 감사합니다. 그렇다면 IOException의 경우에 리콜되지 않을 수 있습니다. 맞습니까? 하지만 SocketException, SSLException, SSLHandshakeException 또는 ConnectException이 발생하면 리콜 될 것입니다. – Arya

+0

예, writer.toString()을 반환하려면 IOException을 incase 한 다음 다시 시도하십시오. IOException의 경우에 작성자를 돌려주는 수정 된 코드, 재 시행을 호출하는 다른 모든 예외 – SomeDude

0

위의 예외가 발생한 경우 어떻게 메소드를 다시 시도 할 수 있습니까?

아래와 같은 방법 중 하나는 getMeta 메서드가 실제로 IOException을 던집니다. 그런 다음 catch 된 예외로 인해 caller 메서드가 재귀 적으로 자체를 호출하게 할 수 있습니다.

나는 그것이

은, 시간의 방법 n 번호로 전화를 인수로 횟수에 전달하고 처리 할 수 ​​있으려면 재 시도하는 방법을 시간을 설정하는 간단한 방법이 희망 이에 따라 정지 기준 논리. getMeta에서

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

: 예를 들어

try{ 
    .... 
}catch(IOException io){ 
    //log or handle io 
    throw io; 
} 

참고 위의 당신이 어떤 방법으로 처리 할 수 ​​있습니다 던진 예외의 기록/논리와 거래를하지 않습니다.

관련 문제