1、拿到OkHttpClient对象OkHttpClient okHttpClient = new OkHttpClient() 2、构造Request对象Request request = new Requ_封装request为cal">
赞
踩
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); } }); } });
注意:::对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();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。