在日常的编写Android软件的过程中,避免不了使用网络请求,但是发http请求是不能在主线程里面发,否则就会出现android.os.NetworkOnMainThreadException的异常,所以必须要放到子线程中处理。步骤如下:
1、将想要请求的图片地址转换成URL类
2、通过openConnection来建立连接
3、在编程的时候避免让用户等,设置网络连接的超时时间,读取时间
4、设置请求网络的类型(GET或者POST)
5、提交网络请求
6、接受返回码,通过返回码判断网络是否请求成功
注意:任何网络请求必须加上网络权限 <uses-permission android:name="android.permission.INTERNET"/>
下面是代码:
/**
* 根据传入url获取到它的图片
*/
private void getBitmap(final String imgUrl) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL bitmapUrl = new URL(imgUrl);
connection = (HttpURLConnection) bitmapUrl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//通过返回码判断网络是否请求成功
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
Bitmap shareBitmap = BitmapFactory.decodeStream(inputStream);
Message message = wxHandler.obtainMessage();
message.what = 0;
message.obj = shareBitmap;
wxHandler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
这里还需要一个Handler来在主线程中设置ImageView的图片
@SuppressLint("HandlerLeak")
private Handler wxHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
Bitmap wxShareBitmap = (Bitmap) msg.obj;
break;
}
}
};