Java连接获取请求异常处理

时间:2016-10-17 18:56:02

标签: java exception-handling get

我正在尝试将GET请求发送到网站,如下所示:

class Area
   has_many :parks, dependent: :destroy
   has_many :houses, dependent: :destroy
end

class Parks
   belongs_to :area
end

class Houses
   belongs_to :area
end   

但是,我需要处理异常。例如,如果抛出异常,那么我将尝试再次请求。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

您可以将whiletry-catch一起使用,如果exception出现,请转到下一次迭代,否则break 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
    }

要限制尝试,只需使用计数变量(尝试)和标志变量来验证成功执行

答案 1 :(得分:2)

我们的想法是将其置于for循环中并使用给定数量的可能尝试次数以便防止无限循环,然后随时发生异常抛出你抓住并记录然后你可以再试一次。如果在固定的尝试次数之后无法完成,则可能会抛出异常。

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