fattah.safa fattah.safa - 1 month ago 9
Java Question

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?

Answer

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

Comments