url.openConnection()远程获取图片缺失

一.现象如下:

 

 

 二.原因分析

      图片未读取完整或者是获取过程中,只取了一次,但服务端可能是分多次返回给你

三.解决办法

  需要控制好读完才停止。怎么确定读完了呢?连接有个方法获取远程资源的长度–getContentLength()

       案列如下:

      

 1 @Test
 2     public void test() {
 3         String urpath="http://localhost:22816/20191217/D77827884/10.146.16.172_01_20191217173949934_TIMING.jpg";
 4         //创建URL
 5         URL url;
 6         try {
 7             // 打开服务器图片路径
 8             url = new URL(urpath);11             //创建连接
12             HttpURLConnection conn=(HttpURLConnection) url.openConnection();
13             conn.setRequestMethod("GET");  // 提交模式
14             conn.setConnectTimeout(10*1000);//连接超时5秒
15             conn.setReadTimeout(10*1000);   //读取超时10秒
16             conn.connect();//连接
17 
18             InputStream input=conn.getInputStream();//获取写数据流
19             int count=conn.getContentLength();//获取远程资源长度
20             byte[] result=new byte[count];
21             int readCount=0;
22             while(readCount<count){//循环读取数据
23                 readCount+=input.read(result,readCount,count-readCount);
24             }
25             InputStream buffin = new ByteArrayInputStream(result);  //把读取完整后的的图片数组转化为输入流
26             FileOutputStream out=new FileOutputStream("D:\\文件表\\cvs\\aa.jpg");
27 
28             // 读取到的数据长度
29             int len;
30             while ((len = buffin.read(result)) != -1) {
31                 out.write(result, 0, len);
32             }
33             // 完毕,关闭所有链接
34             out.close();
35             buffin.close();
36         } catch (MalformedURLException e) {
37             e.printStackTrace();
38         } catch (ProtocolException e) {
39             e.printStackTrace();
40         } catch (IOException e) {
41             e.printStackTrace();
42         }
43 
44     }
posted @ 2019-12-18 14:57  憨憨青年  阅读(864)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css