import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.BASE64Encoder;
/**
* 将网络图片转成Base64码
* @param imgURL网络图片地址。
* 例如:http://***.com/271025191524034.jpg
* @return
*/
public static String imgBase64(String imgURL) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024];
try {
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(100 * 1000);
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "fail";//连接失败/链接失效/图片不存在
}
InputStream inStream = conn.getInputStream();
int len = -1;
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}
注意:sun.misc.BASE64Encoder找不到jar包的解决方法
解决方案1(推荐):
只需要在project build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
解决方案2:
Windows -> Preferences -> Java -> Compiler -> Errors/Warnings ->
Deprecated and trstricted API -> Forbidden reference (access rules): -> change to warning