專案實戰:九、GET請求網路圖片
public void requestHttpGet(String strUrl) throwsException{
public static Bitmap httpGETImage(String string) {
try {
//設定URL
URL url = new URL(string);
//得到HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//連線超時時間
connection.setConnectTimeout(5000);
//讀取超時
connection.setReadTimeout(5000);
//獲取請求碼 一般情況下200是成功
int code = connection.getResponseCode();
//判斷請求碼是否 請求成功
if (code == HttpURLConnection.HTTP_OK) {
//得到資料
InputStream stream = connection.getInputStream();
// 如果是圖片
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}