在之前写过一篇okHttp的封装,这次我将对其做一次更加清楚的描述。话不多说,上代码。
一样,首先导入jar包。
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.12.0'
//布局文件
<?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>
//这里我们写一个工具类okHttpManager
public class okHttpManager{
private OkHttpClient client;
private Handler handler;
private volatile static okHttpManager manager;
//私有化构造函数
private okHttpManager() {
client = new OkHttpClient();
//UI线程
handler = new Handler(Looper.getMainLooper());
}
//定义外部访问方法(单例模式)
public static okHttpManager getInstance() {
okHttpManager instance = null;
synchronized (okHttpManager.class) {
if (instance == null) {
manager = new okHttpManager();
instance = manager;
}
}
return instance;
}
}
接着我们开始封装我们的okhttp
//首先,我们对byte类型的数据进行封装
//异步处理我们的bytes类型的数据
public void asyncRequestBytes(String url, final CallBackByte callback) {
final Request request = new Request.Builder().url(url).build();
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[] bytes = response.body().bytes();
onSuccessBytes(bytes, callback);
}
}
});
}
//定义Bytes类型的返回结果
public void onSuccessBytes(final byte[] valuesByte, final CallBackByte callback) {
//handler.post(R);R处理handler代码块,R的代码实际上就是在UI线程中执行
handler.post(new Runnable() {
@Override
public void run() {
//调用者new CallBackByte()时初始化我们的接口函数
if (callback != null) {
callback.resultByte(valuesByte);
}
}
});
}
//定义回调接口处理数据
interface CallBackByte {
//返回数据为bytes类型
void resultByte(byte[] bytes);
}
就这样,我们只需要在外部调用我们的 asyncRequestBytes()方法就可以了。
//Activity代码如下
public class MainActivity extends AppCompatActivity {
private ImageView iv_picture;
private String url = "https://www.baidu.com/img/bd_logo1.png";
// private String json_path = "http://www.imooc.com/api/teacher?type=4&num=30";
private okHttpManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_picture = (ImageView) findViewById(R.id.iv_picture);
manager = okHttpManager.getInstance();
}
public void button(View view) {
manager.asyncRequestBytes(url, new okHttpManager.CallBackByte() {
@Override
public void resultByte(byte[] bytes) {
Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
iv_picture.setImageBitmap(bitmap);
}
});
}
}
点击按钮后可以在我们的屏幕中间看我图片被加载出来了。
//接下来我们在来对String类型的数据进行封装(思路基本一样)
//异步处理String数据
public void asyncRequestStirng(String url, final CallBcakString callbcakString) {
final Request request = new Request.Builder().url(url).build();
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()) {
String jsonvalues = response.body().string();
Log.i("okHttpManager", jsonvalues);
onSuccessString(jsonvalues, callbcakString);
}
}
});
}
//定义String类型的返回结果
public void onSuccessString(final String data, final CallBcakString callbcakString) {
handler.post(new Runnable() {
@Override
public void run() {
if (callbcakString != null) {
try {
callbcakString.stringdata(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
interface CallBcakString {
void stringdata(String data);
}
//关于其他类型的封装这里就不过多的去阐述了,思路都是一样的。好了,关于这次okhttp的封装就到这,如果想要去理解okhttp源码的同学可以去这里看看。okhttp源码分析
//此博是对老罗okhttp视频的理解及借鉴,老罗CSDN主页