背景:存在数据库的微信图片有 图片失效的情况。所以当用户获取详情的时候会判断一下该微信头像的url是否可用,不可用就直接更新数据库。
import org.apache.commons.lang3.StringUtils;
import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
* 检测微信头像是否可用
*/
public class CheckWXImg {
/**
* 检测微信头像是否可用
* @param url
* @return
*/
public static boolean checkWeChatHeadImg(String url) throws Exception{
if(StringUtils.isEmpty(url)){
return false;
}
HttpURLConnection http = null;
try {
URL urlObj = new URL(url);
if(url.startsWith("https://")){
http = (HttpsURLConnection) urlObj.openConnection();
}else{
http = (HttpURLConnection) urlObj.openConnection();
}
http.setRequestMethod("GET");
http.setConnectTimeout(30 * 1000);
http.setReadTimeout(30 * 1000);
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36");
http.setDefaultUseCaches(false);
http.connect();
Map<String, List<String>> resHeaders = http.getHeaderFields();
for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
String name = entry.getKey();
if ("X-ErrNo".equalsIgnoreCase(name)) {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (http != null) {
http.disconnect();
}
}
return true;
}
}
原文转载: https://blog.csdn.net/weixin_39517591/article/details/102836673