private static byte[] httpsConverBytes(String fileUrl) { BufferedInputStream inStream = null; ByteArrayOutputStream outStream = null; try { TrustManager[] tm = {new TrustAnyTrustManager()}; SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE"); sc.init(null, tm, new java.security.SecureRandom()); URL console = new URL(fileUrl); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.connect(); inStream = new BufferedInputStream(conn.getInputStream()); outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } byte[] content = outStream.toByteArray(); return content; } catch (Exception e) { e.printStackTrace(); } finally { if (null != inStream) { try { inStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != outStream) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } 代码优化
时间: 2024-02-10 17:29:22 浏览: 144
这段代码可以进行一些优化,例如使用try-with-resources语句来自动关闭流,以及使用更现代的API来简化操作。下面是优化后的代码示例:
private static byte[] httpsConverBytes(String fileUrl) {
try {
TrustManager[] tm = {new TrustAnyTrustManager()};
SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
sc.init(null, tm, new java.security.SecureRandom());
URL console = new URL(fileUrl);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
try (BufferedInputStream inStream = new BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return outStream.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
通过使用try-with-resources语句,可以自动关闭输入流和输出流,无需手动处理异常。此外,去掉了不必要的null检查和关闭流的逻辑判断。
阅读全文