4、OKHttp详解
https://www.jianshu.com/p/9aa969dd1b4d
在AndroidManifest.xml中加入联网权限
<uses-permission android:name="android.permission.INTERNET" />
1、拿到OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient()
2、构造Request对象
Request request = new Request.Builder()
.get()
.url("https:www.baidu.com")
.build();
这里我们采用建造者模式和链式调用指明是进行Get请求,并传入Get请求的地址
如果我们需要在get请求时传递参数,我们可以以下面的方式将参数拼接在url之后
https:www.baidu.com?username=admin&password=admin
3、将Request封装为Call
Call call = client.newCall(request);
4、根据需要调用同步或者异步请求方法
//同步调用,返回Response,会抛出IO异常
Response response = call.execute();
//异步调用,并设置回调函数
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(OkHttpActivity.this, "get failed", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String res = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
contentTv.setText(res);
}
});
}
});
- 同步调用会阻塞主线程,一般不适用
- 异步调用的回调函数是在子线程,我们不能在子线程更新UI,需要借助于runOnUiThread()方法或者Handler来处理
注意:::对okHttp连接超时进行处理
public void onFailure(Call call, IOException e) {
Log.e(TAG, mPlayInfo.getPdfilename() + "下载进度:连接失败-" + e.getMessage());
// 失败终端线程
if(e instanceof SocketTimeoutException && serversLoadTimes<BaseConstant.maxLoadTimes){如果超时并未超过指定次数,则重新连接
Log.e(TAG, mPlayInfo.getPdfilename() + "下载进度:超时" + e.getMessage()+"尝试第 "+serversLoadTimes+" 次");
serversLoadTimes++;
okHttpClient.newCall(call.request()).enqueue(this);
}else {
Log.e(TAG, mPlayInfo.getPdfilename() + "下载出错" + e.toString());
interrupt();
}
}