Android网络请求开源库Android知识Android开发

OkHttp3-从零开始的详细使用到简单封装

2017-02-24  本文已影响2867人  iam薛定諤

Github地址---MyOkhttpUtils

初衷

对于okhttp3出来以后,使用的都是网上封装好的库,为了更好地理解封装的内容,对okhttp本身的熟悉,肯定学一下子了,网上okhttp的方法很多,但是网上okhttp3方面的东西并不多,很多都过时的方法,总结了一下,讲了一下okhttp3的基本使用方法,在下边要耐心才会 。
封装了一下基本大家使用得到的功能,想用的话可以直接拿去用,想扩展的话也可以直接下载扩展,代码比较少,不了解okhttp的可以下载学习一下,大神门口右走吧。
封装逻辑和使用的好多方法找不到,借鉴了两位大神的逻辑,相当于简化版本吧,封装的比较全面的可以参照
hongyangAndroid / okhttputils
jeasonlzy/okhttp-OkGo

本文中库的简单使用介绍

在app中添加依赖

    dependencies {
        compile 'com.github.jlcclidong:MyOkhttpUtils:0.10'
    }

okhttp本身的基本使用

打印response时注意,如果添加了interceptor则不能直接调用response.body().string()方法,调用此方法会直接close掉这个response,在callback中得不到正确的结果会报异常,只能使用response.newbuilder() 方法来使用新创建的response调用,eg
private Response logForResponse(Response response, long time) {
try {
Log.e("============response start==============");
//response.body().string()只能调用一次 body()就会关掉
//每次使用前都clone一份使用保证原来的body没有被关掉
Response copy = response.newBuilder().build();
Log.e("responseurl:" + copy.request().url());
Log.e("response code:" + copy.code());
Log.e("total time:" + time);
if (!TextUtils.isEmpty(copy.message()))
Log.e("message:" + copy.message());
if (copy.headers() != null && copy.headers().size() > 0)
Log.e("headers:" + copy.headers().toString());
Log.e("============response end================");
ResponseBody body = copy.body();
if (body != null) {
MediaType mediaType = body.contentType();
if (mediaType != null) {
Log.e("============response body===============");
Log.e("Content-type:" + mediaType.toString());
if (isText(mediaType)) {
String content = body.string();
Log.e(JsonFormat.formatJson(content));
Log.e("============response body===============");
return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
} else {
Log.e(" maybe response content too large too print , ignored!");
}
}
} else {
Log.e(" body is null , ignored!");
}
} catch (Exception e) {
Log.e("log response has something worng!!");
}
return response;
}
这样每次调用http请求是就可以详细监听其中的内容了
全部具体内容详见github代码

最后

好像没什么了 ,感觉有帮助的帮忙点个star,辣眼睛了的我也没办法

啦啦啦啦.gif
上一篇下一篇

猜你喜欢

热点阅读