OkHttp3简单拦截器

先写一个类:用于okhttp中去实现
(附加单例模式)

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //拿到Request对象
        Request request = chain.request();

        long t1 = System.nanoTime();
        System.out.println(" request  = " + String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        //拿到Response对象
        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        //得出请求网络,到得到结果,中间消耗了多长时间
        System.out.println("response  " + String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }
}

然后去okhttp中去调用



public class HttpUtil {

    private static HttpUtil mHttpUtil;
    private final Handler handler;
    private final OkHttpClient client;

    public HttpUtil(){
        handler = new Handler(Looper.myLooper());

        LoggingInterceptor logging = new LoggingInterceptor();
client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .connectTimeout(5, TimeUnit.SECONDS)
        .writeTimeout(5, TimeUnit.SECONDS)
        .readTimeout(5, TimeUnit.SECONDS)
        .build();
    }

    public static HttpUtil getInterface(){
        if (mHttpUtil == null){
            synchronized (HttpUtil.class){
                if(mHttpUtil == null){
                    mHttpUtil = new HttpUtil();
                }
            }
        }
        return mHttpUtil;
    }

    public void doPost(String url, Map<String ,String > map , final HttpUtilInterface httpUtilInterface){
        FormBody.Builder form = new FormBody.Builder();

        if (map != null) {
            for (String key : map.keySet()) {
                form.add(key, map.get(key));
            }
        }

        FormBody body = form.build();

        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        httpUtilInterface.HttpFailure();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        httpUtilInterface.HttpResponse(json);
                    }
                });
            }
        });
    }

}


即可

发布了15 篇原创文章 · 获赞 8 · 访问量 3296
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览