- 网络请求的方法有很多种,有HttpClient、HttpURLConnection 、还有一些网络的框架,比如大家常用的Volley和xUtils,本文给大家讲解的 是原生的网络请求HttpURLConnection;
- 因为网络请求是个耗时操作,所以肯定要用到线程
3. `public void downLoad(){
new Thread(new Runnable(){
@Override
public void run(){
try{
Url url = new Url("http://www.baidu.com/img/bd_logo1.png");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setResquestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if(code == 200){
InputStream inputStream = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
runOnUiThread(new Runnable(){
@Override
public void run(){
imageView.setImageBitmap(bitmap);
}
});
}
}catch(Expection e){
}finally{
inputStream.close();
}
}
}).start();
4. }`