//發送http請求
try {
//1.使用網址構造一個URL對象
URL url = new URL(path);
//2.獲取連接對象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3.設置一些屬性
//設置請求方式,注意大寫
conn.setRequestMethod("GET");
//設置請求超時
conn.setConnectTimeout(8000);
//設置讀取超時
conn.setReadTimeout(8000);
//4.發送請求,建立連接
conn.connect();
//5.判斷請求是否成功
if(conn.getResponseCode() == 200){
//獲取服務器返回的流,流里就是客戶端請求的數據
InputStream is = conn.getInputStream();
//讀取流里的數據,構造出一張圖片
Bitmap bm = BitmapFactory.decodeStream(is);
//把下載的圖片顯示至imageview
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);
}
else{
Toast.makeText(this, "請求失敗鳥o(╯□╰)o", 0).show();
}
} catch (Exception e) {
e.printStackTrace();
}