1、根據圖片的url獲取圖片內容,賦值到字節數組中
byte[] bytes = new byte[0];
if (StringUtils.isNotEmpty(imgUrl)) {
//TODO 此處待抽取helper
HttpURLConnection connection = null;
// 創建遠程url連接對象
URL connecUrl = new URL(imgUrl);
// 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
connection = (HttpURLConnection) connecUrl.openConnection();
// 設置連接方式:get
connection.setRequestMethod("GET");
// 設置連接主機服務器的超時時間:15000毫秒
connection.setConnectTimeout(15000);
// 設置讀取遠程返回的數據時間:60000毫秒
connection.setReadTimeout(60000);
// 發送請求
connection.connect();
// 通過connection連接,獲取輸入流
InputStream is = null;
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
}
if(null != is){
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
is.close();
bytes = bos.toByteArray();
}
}