初始OkHttp框架(OkHttp简单应用)
随着Android系统的不断成长,随之而来的网络框架也逐渐增多。这里我们就对如今很火的一款网络开源框架进行讲解——OkHttp
首先我们需要应用其jar包,如下:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.12.0'
接着我们就用代码来简单的使用下我们的okHttp
首先来看一下我们的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="button"
android:text="按钮"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
很简单,就一个Button和一个ImageView,我们通过点击Button来加载我们的ImageView。
//在我们的代码中引入布局文件
private ImageView iv_picture;
private String url="https://www.baidu.com/img/bd_logo1.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_picture= (ImageView) findViewById(R.id.iv_picture);
}
//定义一个Handler来更新我们的ImageView
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
byte[] bytes = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
iv_picture.setImageBitmap(bitmap);
break;
default:
break;
}
}
};
//实现我们的button点击方法
public void button(View view){
//构建一个get请求
final Request request=new Request.Builder().url(url).build();
//需要一个OkHttpClient对象
OkHttpClient client=new OkHttpClient();
//new Call
Call call = client.newCall(request);
//放入异步请求队列进行处理
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//出现错误直接打印输出
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//如果响应结果不为空并且响应成功
if(response!=null&&response.isSuccessful()){
//获取到我们的byte
byte[] bytes = response.body().bytes();
Message mes=new Message();
mes.what=1;
mes.obj=bytes;
//发送给Handler处理,因为我们这里并不是UI线程
handler.sendMessage(mes);
}
}
});
}
//响应的注解我已经在代码中一一说明了,这里就不在阐述了。但是还有一点我们不能忘了,就是我们需要在我们的Manifest.xm中写入我们的网络权限
<uses-permission android:name="android.permission.INTERNET"/>
好了,到这里我们就对okHttp有一个了解了。不过你有没有发现,如果我们此时想要对另一个图片进行网络加载,我们是不是又要构建一个Request请求呢,答案是肯定的,这样就会导致我们写很多的重复代码。所以接下来我们就来对我们的okHttp框架进行再一次的封装。