先看知乎:https://www.zhihu.com/question/35044484
场景: 微信上传了图片素材,返回了图片url,然后不能在img标签中正常显示.
原因是微信做了图片防盗连接.
解决方法:
原理:使用你的服务端脚本,远程抓取图片,然后输出image/* 格式,就可以了。
java方法:
1 @RequestMapping("/img") 2 @ResponseBody 3 public void aa1(@NotNull String url, HttpServletRequest request, HttpServletResponse response) throws IOException { 4 5 if (!StringUtil.isEmpty(url)) { 6 int index=url.indexOf("http"); 7 if(index==-1){ 8 url="http://"+url; 9 } 10 URL getUrl = new URL(url); 11 URLConnection connection = getUrl.openConnection(); 12 connection.setRequestProperty("Referer", ""); 13 connection.setRequestProperty("accept", "*/*"); 14 connection.setRequestProperty("connection", "Keep-Alive"); 15 connection.setRequestProperty("user-agent", 16 "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36"); 17 connection.setDoOutput(true); 18 InputStream fis = connection.getInputStream(); 19 OutputStream os = response.getOutputStream(); 20 int count = 0; 21 byte[] buffer = new byte[1024 * 1024]; 22 while ((count = fis.read(buffer)) != -1) { 23 os.write(buffer, 0, count); 24 } 25 os.flush(); 26 fis.close(); 27 response.setContentType("image/*"); 28 } 29 }
url是微信的图片连接.