根据Url抓取图片在浏览器显示

本文探讨了在抓取不同网站图片时遇到的格式不匹配问题,详细解释了如何通过检查和设置响应头中的Content-Type和Content-Encoding来解决图片显示异常的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 抓取了不同网站的图片,其中一个可以显示,另一个提示格式不对,在浏览器里对比了两个图片的响应头,不同之处是一个经过了压缩

在Response里对其进行设置

response.setHeader("Content-Encoding","gzip");

完整代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        String USER_AGENT = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
            //图片的url
	        String strUrl = request.getParameter("url");
	  
	        ServletOutputStream out = null;
	        try {    
	            URL url = new URL(strUrl);
	            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
	            conn.setRequestProperty("User-Agent", USER_AGENT);
	            conn.setRequestMethod("GET");
	            conn.setConnectTimeout(5 * 1000);
	           
	            InputStream inStream = conn.getInputStream();
	            String contentType = conn.getHeaderField("Content-Type");
                    //设置返回的图片格式
	            if(null != contentType){
	                response.setContentType(contentType);
	                System.out.println("Content-Type:  "+contentType);
	            }
                    //设置返回的编码格式
	            String contentEncoding = conn.getHeaderField("Content-Encoding");
	            if(null != contentEncoding){
	                response.setHeader("Content-Encoding",contentEncoding);
	                System.out.println("Content-Encoding:  "+contentEncoding);
	            }
	            out = response.getOutputStream();
	            int len = 0;
	            byte[] byteImg = new byte[2048];
	            while((len = inStream.read(byteImg)) != -1){
	                out.write(byteImg,0, len);
	            }
	            
	            out.flush();
	        } catch (Exception e) {
	        }finally{
	            try {
	                if(null != out)
	                out.close();
	            } catch (IOException e) {
	            }
	        }
		
		
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值