不想做厨师的程序员不是好农民 2019-01-13 18:04 采纳率: 0%
浏览 2384

InputStream 读取不完整求解

public static String getImageStr(String urlString){
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开URL连接
            URLConnection con = url.openConnection();
            InputStream is = null;
            byte[] data = null;
            try {
                is = con.getInputStream();
                data = new byte[is.available()];
                is.read(data);
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 加密
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

urlString 下载到文件流。

我需要把把流转成base64编码的字符串,就给接口调用方。他们解析出来的图片基本都是不完整的。不知道这的哪里读取除了问题。请教大神改改。万分感谢。

  • 写回答

1条回答 默认 最新

  • 孤独不是寂寞 2019-01-14 08:52
    关注

    这个我之前也有过这个问题,后来有了解决办法
    URL url;
    byte[] data = null;
    try {
    url = new URL(fujianurl);
    HttpURLConnection hconn = (HttpURLConnection)url.openConnection();

    hconn.setRequestMethod("POST");
    hconn.setConnectTimeout(30 * 1000);
    inStream = hconn.getInputStream();//通过输入流获取图片数据

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
            byte[] buffer = new byte[1024];    
            int len = 0;    
            while( (len=inStream.read(buffer)) != -1 ){    
                outStream.write(buffer, 0, len);    
            }    
            data = outStream.toByteArray();  
            outStream.close();
        } catch (Exception e1) {
            System.out.println(e1.getMessage());
            return true;
        }
        最后这个data得到的是完整的图片。
        具体原因应该和传递文件的大小相关,我传递小的图片很少遇到这样的问题。
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料