java读取远程图片缺失或者不全问题解决

造成原因:

      1、网络丢包    2、获取过程中,只取了一次,但服务端可能是分多次返回给你

解决方法:

      1、确认服务端是否返回ContentLength

response.setContentLengthLong(file1.length()); 

      2、调用时使用以下代码:获取总长度,读完后才停止

public static String urlToString(String imgUrl){
        byte[] result=null;
        InputStream inStream=null;
        String photo = "";
        try {
            //创建URL
            URL url=new URL(imgUrl);
            //创建连接
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5*1000);
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.connect();

            inStream=conn.getInputStream();
            int count=conn.getContentLength();//获取远程资源长度
            result=new byte[count];
            int readCount=0;
            while(readCount<count){//循环读取数据
                readCount+=inStream.read(result,readCount,count-readCount);
            }
            photo = toBase64(result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取远程图片失败", e);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (conn!= null) {
                    conn.disconnect();
                }
            } catch (IOException e) {
                log.error("文件处理错误!", e);
            }
            log.info("o==||=====>读取图片返回");
        }
        return photo;
    }
    private static String toBase64(byte[] imgData) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(imgData);
    }

参考博客:https://blog.csdn.net/open_yu/article/details/80008289

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值