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编码的字符串,就给接口调用方。他们解析出来的图片基本都是不完整的。不知道这的哪里读取除了问题。请教大神改改。万分感谢。
这个我之前也有过这个问题,后来有了解决办法
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得到的是完整的图片。
具体原因应该和传递文件的大小相关,我传递小的图片很少遇到这样的问题。