1. 程式人生 > >Http協議獲取圖片資料流(GET方式)

Http協議獲取圖片資料流(GET方式)

String filePath = "http://127.0.0.1/doc/pic.jpg";

byte[] byteArray;
HttpURLConnection connection = null;
if(StringUtils.isEmptyString(filePath)){
    return;
}
try {
    URL url = new URL(filePath);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(5
*1000); InputStream in = connection.getInputStream(); try { byteArray = readInputStream(in); } catch (Exception e) { log.error("error:"+e.getStackTrace()); throw new Exception("圖片轉換BYTE流失敗!"); } } catch (IOException e2) { if(log.isErrorEnabled()){ log.error("error:"
+e2.getStackTrace() +"getMessage:"+e2.getMessage()); } throw new Exception("獲取照片資訊失敗!"); } //獲取照片資料流 if(byteArray != null){ datamodel.setModelChangeImageObject("Picture",byteArray); } connection.disconnect(); } private static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new
ByteArrayOutputStream(); byte[] buffer = new byte[1024]; //建立一個Buffer字串 //每次讀取的字串長度,如果為-1,代表全部讀取完畢 int len = 0; //使用一個輸入流從buffer裡把資料讀取出來 while( (len=inStream.read(buffer)) != -1 ){ //用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度 outStream.write(buffer, 0, len); } inStream.close(); //關閉輸入流 return outStream.toByteArray(); //把outStream裡的資料寫入記憶體 }