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


版权声明:本文为jin110502116原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。