前言:
这也算是开年第一篇,上个实用奏效的OkHttp3网络请求 ,这是一个高效地使用HTTP能让资源加载更快,节省带宽。
OkHttp:
Okhttp是一个处理网络请求的开源项目,是安卓最火热的轻量级框架。
据说哪怕你默认网络出现问题的时候OkHttp依然坚守自己的职责,它会自动恢复一般的连接问题,如果你的服务有多个IP地址,当第一个IP请求失败时,OkHttp会交替尝试你配置的其他IP呢。
我这里面用的单例模式饿汉模式,内置封装了拦截器,异步Get请求和Post请求。
想具体了解网络编程Http原理的可点击http://blog.csdn.net/itachi85/article/details/51190687
使用步骤:
- 网络权限
<uses-permission android:name="android.permission.INTERNET"/>- 导入依赖
//okhttp implementation 'com.squareup.okhttp3:okhttp:3.2.0' implementation 'com.squareup.okio:okio:1.7.0' //拦截器 implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
public class OkHttpUtils {
/**
* 单例模式
*/
private static OkHttpUtils okHttpUtils = null;
private OkHttpUtils() {
}
public static OkHttpUtils getInstance() {
//双层判断,同步锁
if (okHttpUtils == null) {
synchronized (OkHttpUtils.class) {
okHttpUtils = new OkHttpUtils();
}
}
return okHttpUtils;
}
/**
* 单例模式
* 封装OkhHttp
* synchronized同步方法
*/
private static OkHttpClient okHttpClient = null;
private static synchronized OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
//拦截器
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//拦截日志消息
Log.i("lj", "log: " + message);
}
});
//设置日志拦截器模式
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
}
return okHttpClient;
}
/**
* doGet
*/
public void doGet(String url, Callback callback) {
//创建okhttp
OkHttpClient okHttpClient = getOkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
/**
* doPost
*/
public void doPost(String url, Map<String, String> params, Callback callback) {
OkHttpClient okHttpClient = getOkHttpClient();
//请求体
FormBody.Builder formBody = new FormBody.Builder();
for (String key : params.keySet()) {
//遍历map集合
formBody.add(key, params.get(key));
}
Request request = new Request.Builder()
.url(url)
.post(formBody.build())
.build();
okHttpClient.newCall(request).enqueue(callback);
}
}