gpt4 book ai didi

Java连接Get请求异常处理

转载 作者:行者123 更新时间:2023-11-30 06:08:17 25 4
gpt4 key购买 nike

我尝试向网站发送 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();

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

最佳答案

您可以将 whiletry-catch 一起使用,因此如果发生异常,则转到下一次迭代,否则break 循环

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
}

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

关于Java连接Get请求异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com