用HttpURLConnection发送http请求

//发送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();
}
posted @ 2017-02-13 13:43  SoulCode  阅读(532)  评论(0编辑  收藏  举报