判断http、https图片是否存在

source是String类型的图片地址

方式一:

try {  
     URL url = new URL(source); 
     URLConnection uc = url.openConnection();
     InputStream in = uc.getInputStream(); // 如果图片不存在则这一步异常
     if (source.equalsIgnoreCase(uc.getURL().toString())) 
         in.close();  
     System.out.println("图片存在");
} catch (Exception e) {  
     System.out.println("图片不存在");
}

方式二:

try {  
      URL url = new URL(source); 
      URLConnection uc = url.openConnection();
      if(HttpURLConnection.HTTP_OK ==((HttpURLConnection)uc).getResponseCode());
      System.out.println("图片存在");
} catch (Exception e) {  
      System.out.println("图片不存在");
}

方式三:

boolean isExist = new UrlResource(source).exists();

方式四:Hutool工具

try {
      HttpResponse resp = HttpRequest.head(source).timeout(7000).execute();
      return resp.getStatus() == HttpStatus.HTTP_OK && resp.header(Header.CONTENT_TYPE).startsWith("image/") 
         && Convert.toLong(resp.header(Header.CONTENT_LENGTH)).longValue() > 0;
} catch (Exception e) {
      e.printStackTrace();
}

你可能感兴趣的:(Java,http,网络协议,网络,java,https)