fattah.safa
fattah.safa

Reputation: 966

Java Connection Get Request Exception Handling

I'm trying to send GET request to a website as follows:

uRL = new URL(URLString);
connection = (HttpURLConnection) uRL.openConnection();    
// optional default is GET
connection.setRequestMethod("GET");    
// add request header
connection.setRequestProperty("User-Agent", USER_AGENT);    
responseCode = connection.getResponseCode();

However, I need to handle exceptions. For example, if exception is thrown then I will try to request again. How can I do that?

Upvotes: 2

Views: 2866

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

you can use while with try-catch so if an exception occur go to next iteration otherwise break the loop

int attempts=5;
boolean flag=false;
while(attempts-- > 0){
  try{
   uRL = new URL(URLString);
   connection = (HttpURLConnection) uRL.openConnection();    
   connection.setRequestMethod("GET");    
   connection.setRequestProperty("User-Agent", USER_AGENT);    
   responseCode = connection.getResponseCode();
   flag=ture;
    break;
  }catch(Exception e){
      e.printStackTrace();
      continue;
    }
}


 if(flag){
     // mean request executed successfully 
     // don't throw exception, unless you want to break the current flow of execution
    }

To limit the attempts , simply use a count variable(attempt) and a flag variable to verify the successful execution

Upvotes: 3

Nicolas Filotto
Nicolas Filotto

Reputation: 44995

The idea is to put it into a for loop with a given amount of possible tries in order to prevent an infinite loop, then anytime an exception is thrown you catch it and log it then you can try again. If it could not be done after the fixed amount of tries you could throw an exception.

boolean success = false;
for (int i = 1; !success && i <= maxTries; i++) {
    try {
        uRL = new URL(URLString);
        connection = (HttpURLConnection) uRL.openConnection();
        // optional default is GET
        connection.setRequestMethod("GET");
        // add request header
        connection.setRequestProperty("User-Agent", USER_AGENT);
        responseCode = connection.getResponseCode();
        success = true;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Could not access to the server due to {}, try {}/{}", 
            new Object[]{e.getMessage(), i, maxTries}
        );
    }
}
if (!success) {
    throw new IllegalStateException("Could not access to the server");
}

Upvotes: 2

Related Questions