通過HttpURLConnection獲取圖片以及inputStream
阿新 • • 發佈:2018-12-16
import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetImg { public void getImg(){ try { String imgAddress = "http://cdn.haoceyan.com/584_GLTTLXJ6_1025U4B5YFL7_1_1?imageMogr/auto-orient/crop/!106x28a60a441/quality/80" URL url = new URL(imgAddress); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 設定連線超時時間 conn.setConnectTimeout(3000); InputStream inputStream = null; // 正常響應時獲取輸入流, 在這裡也就是圖片對應的位元組流 if (conn.getResponseCode() == 200) { inputStream = conn.getInputStream(); System.out.println(inputStream.available()); } byte[] buffer = new byte[1024]; int length = 0; // 這裡是輸出到工程根目錄下 FileOutputStream fileOutputStream = new FileOutputStream("d://myavatar.jpg"); // 將輸入流迴圈寫到關聯檔案的輸出流 while ((length = inputStream.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, length); } System.out.println("end"); // 釋放資源 inputStream.close(); fileOutputStream.close(); }catch (Exception e) { e.printStackTrace(); } } }