一. 现象如下:
二. 原因分析
图片未读取完整或者是获取过程中, 只取了一次, 但服务端可能是分多次返回给你
三. 解决办法
需要控制好读完才停止. 怎么确定读完了呢? 连接有个方法获取远程资源的长度 - getContentLength()
案列如下:
- @Test
- public void test() {
- String urpath="http://localhost:22816/20191217/D77827884/10.146.16.172_01_20191217173949934_TIMING.jpg";
- // 创建 URL
- URL url;
- try {
- // 打开服务器图片路径
- url = new URL(urpath);11 // 创建连接
- HttpURLConnection conn=(HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET"); // 提交模式
- conn.setConnectTimeout(10*1000);// 连接超时 5 秒
- conn.setReadTimeout(10*1000); // 读取超时 10 秒
- conn.connect();// 连接
- InputStream input=conn.getInputStream();// 获取写数据流
- int count=conn.getContentLength();// 获取远程资源长度
- byte[] result=new byte[count];
- int readCount=0;
- while(readCount<count){// 循环读取数据
- readCount+=input.read(result,readCount,count-readCount);
- }
- InputStream buffin = new ByteArrayInputStream(result); // 把读取完整后的的图片数组转化为输入流
- FileOutputStream out=new FileOutputStream("D:\\ 文件表 \\cvs\\aa.jpg");
- // 读取到的数据长度
- int len;
- while ((len = buffin.read(result)) != -1) {
- out.write(result, 0, len);
- }
- // 完毕, 关闭所有链接
- out.close();
- buffin.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (ProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
来源: http://www.bubuko.com/infodetail-3337707.html