gpt4 book ai didi

java - 使用 HttpClient 获取 URL 状态代码的最快方法是什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:03:19 32 4
gpt4 key购买 nike

使用 HttpClient 获取 URL 状态的最快方法是什么?我不想下载页面/文件,我只想知道页面/文件是否存在?(如果是重定向我希望它跟随重定向)

最佳答案

下面是我非常喜欢的从HttpClient获取状态码的方法:

public boolean exists(){
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpHead headReq = new HttpHead(this.uri);
response = client.execute(headReq);
StatusLine sl = response.getStatusLine();
switch (sl.getStatusCode()) {
case 404: return false;
default: return true;
}

} catch (Exception e) {
log.error("Error in HttpGroovySourse : "+e.getMessage(), e );
} finally {

try {
response.close();
} catch (Exception e) {
log.error("Error in HttpGroovySourse : "+e.getMessage(), e );
}
}

return false;
}

关于java - 使用 HttpClient 获取 URL 状态代码的最快方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12145942/

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