【问题标题】:Java Connection Get Request Exception HandlingJava 连接获取请求异常处理
【发布时间】:2016-10-17 18:56:01
【问题描述】:

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

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();

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

【问题讨论】:

    标签: java exception-handling get


    【解决方案1】:

    您可以将while 与try-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
        }
    

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

    【讨论】:

    • 标志在while循环中应该为真而不是真的
    【解决方案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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2019-10-04
      • 2020-06-24
      • 2021-03-06
      • 1970-01-01
      • 2013-03-19
      相关资源
      最近更新 更多