1414import java .lang .reflect .Field ;
1515import java .lang .reflect .InvocationTargetException ;
1616import java .lang .reflect .Method ;
17+ import java .net .ConnectException ;
1718import java .net .HttpURLConnection ;
1819import java .net .URL ;
1920import java .net .URLEncoder ;
@@ -34,6 +35,7 @@ public abstract class APIResource extends PingppObject {
3435
3536 public static int CONNECT_TIMEOUT = 30 ;
3637 public static int READ_TIMEOUT = 80 ;
38+ public static int RETRY_MAX = 1 ;
3739
3840 /**
3941 * Http requset method
@@ -608,21 +610,31 @@ protected static <T> T request(APIResource.RequestMethod method, String url, Map
608610 }
609611
610612 PingppResponse response ;
611- try {
612- // HTTPSURLConnection verifies SSL cert by default
613- response = makeURLConnectionRequest (method , url , query , Pingpp .apiKey );
614- if (Pingpp .DEBUG ) {
615- System .out .println (getGson ().toJson (response ));
613+ int retryCount = 0 ;
614+ while (true ) {
615+ try {
616+ // HTTPSURLConnection verifies SSL cert by default
617+ response = makeURLConnectionRequest (method , url , query , Pingpp .apiKey );
618+ if (Pingpp .DEBUG ) {
619+ System .out .println (getGson ().toJson (response ));
620+ }
621+
622+ int rCode = response .getResponseCode ();
623+ String rBody = response .getResponseBody ();
624+ if (rCode < 200 || rCode >= 300 ) {
625+ handleAPIError (rBody , rCode );
626+ }
627+ return getGson ().fromJson (rBody , clazz );
628+ } catch (ClassCastException ce ) {
629+ throw ce ;
630+ } catch (ConnectException e ) {
631+ if (retryCount < RETRY_MAX ) {
632+ retryCount ++;
633+ } else {
634+ throw new APIConnectionException (e .getMessage (), e );
635+ }
616636 }
617- } catch (ClassCastException ce ) {
618- throw ce ;
619637 }
620- int rCode = response .getResponseCode ();
621- String rBody = response .getResponseBody ();
622- if (rCode < 200 || rCode >= 300 ) {
623- handleAPIError (rBody , rCode );
624- }
625- return getGson ().fromJson (rBody , clazz );
626638 }
627639
628640 /**
@@ -636,7 +648,7 @@ protected static <T> T request(APIResource.RequestMethod method, String url, Map
636648 */
637649 private static void handleAPIError (String rBody , int rCode )
638650 throws InvalidRequestException , AuthenticationException ,
639- APIException , ChannelException , RateLimitException {
651+ APIException , ChannelException , RateLimitException , ConnectException {
640652 APIResource .Error error = getGson ().fromJson (rBody ,
641653 APIResource .ErrorContainer .class ).error ;
642654 switch (rCode ) {
@@ -650,6 +662,8 @@ private static void handleAPIError(String rBody, int rCode)
650662 throw new ChannelException (error .toString (), error .param , null );
651663 case 401 :
652664 throw new AuthenticationException (error .toString ());
665+ case 502 :
666+ throw new ConnectException (error .toString ());
653667 default :
654668 throw new APIException (error .toString (), null );
655669 }
0 commit comments