2016-07-06 6 views
4

Ich habe die folgende Methode, die einen Proxy verwendet, um Informationen von einem Server abzurufen. Manchmal aufgrund einer schlechten Proxy ich SocketException bekommen, SSLException, SSLHandshakeException oder ConnectExceptionVersuchen Sie Methode auf bestimmten Ausnahmen

Wie Sie in meiner Methode sehen kann ich schon bin mit catch (IOException ioe) ich tun muss, dass, um den Inhalt der Serverantwort zu erhalten, wenn der Server etwas zurückgibt anders als Code 200.

Wie kann ich die Methode wiederholen im Falle der oben genannten Ausnahmen?

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

Verwenden Sie eine Schleife oder Rekursion. Wenn Sie diesen Kram und endlose Rekursion/Schleifen vermeiden wollen, setzen Sie einfach alles aus dem Try-Block ohne zusätzliche Logik in eine neue Methode. Welche können Sie dann ein anderes Mal anrufen. – HopefullyHelpful

+1

'Wie kann ich die Methode wiederholen lassen? Möchten Sie es erneut versuchen oder kontinuierlich wiederholen, bis keine Ausnahme ausgelöst wird? – copeg

+0

@copeg Ich hoffe, es gibt eine einfache Möglichkeit zu bestimmen, wie oft es versuchen sollte, aber es ist zu kompliziert, ich werde es nur einmal versuchen. – Arya

Antwort

0

So wie ich das tun würde, ist eine neue Wiederholungsmethode erstellen und am Ende Ihres getMeta() -Methode aufrufen, so dass es in nur im Fall von Anomalien genannt wird Ich gehe davon aus Sie nur die Wiederholungs nennen sollte ein paar mal und damit getMeta sollen einige Ausnahme wie RetryException nach bestimmten Anzahl von Malen

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

} 

Wenn eine Ausnahme in Ihrem getMeta geworfen wird() werfen, fängt seine Sachen tun, wie Sie sich jetzt tun, aber danach, retryGetMeta heißt

+0

Danke für die Antwort, so würde dies im Falle von IOException nicht zurückgerufen werden, oder? aber es wird zurückgerufen, wenn SocketException, SSLException, SSLHandshakeException oder ConnectException ausgelöst wird? – Arya

+0

Ja, wenn Sie writer.toString() in Verbindung mit IOException zurückgeben wollen, wird der Wiederholungsversuch nicht aufgerufen. Imodifizierter Code, um den Writer im Falle von IOException zurückzugeben, alle anderen Ausnahmen werden erneut aufgerufen – SomeDude

0

Wie kann ich die Methode im Falle der obigen Ausnahmen wiederholen?

Eine Möglichkeit, die unten gezeigt wird, ist, dass die Methode getMeta tatsächlich die IOException auslöst. Sie können dann eine caller Methode rekursiv aufrufen, da alle Exceptions abgefangen wurden.

Ich hoffe, es ist eine einfache Art und Weise der Einstellung, wie die Zeiten es erneut versuchen sollte

Lage sein, die Methode n Anzahl von Malen zu nennen, in der Anzahl, wie oft als Argument übergeben und sie mit die Stopkriterium Logik entsprechend. Zum Beispiel:

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

In getMeta:

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

Beachten Sie die oben befasst sich nicht mit der Protokollierung/Logik der geworfen Ausnahmen, die Sie in irgendeiner Weise zu handhaben möchten.

Verwandte Themen