将url图片转化成Base64字符串返回StringBuilder
(忽略证书验证)
public StringBuilder getImageBase64StrFromUrl(String imgSrc) throws Exception {
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLsConnection httpsUrl = null;
StringBuilder sb = new StringBuilder();
try {
//忽略证书验证
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
url = new URL(imgSrc);
httpsUrl = (HttpURLConnection) url.openConnection();
httpsUrl.setRequestMethod("GET");
httpsUrl.setConnectTimeout(30 * 1000);
//httpsUrl.setReadTimeout(30 * 1000);
httpsUrl.connect();
httpsUrl.getInputStream();
is = httpsUrl.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
BASE64Encoder encoder = new BASE64Encoder();
return sb.append(encoder.encode(outStream.toByteArray()));
} catch (Exception e) {
throw new Exception(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpsUrl != null) {
httpsUrl.disconnect();
}
}
}
private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
private static class TrustAllManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
}