使用OkHttp的Interceptor模拟返回数据

来源:互联网 发布:linux php 权限 编辑:程序博客网 时间:2024/05/21 22:55

使用OkHttp的Interceptor模拟返回数据

在开发安卓客户端的时候,我们会碰到服务器尚未部署的情况,而我们又需要数据进行调试,这个时候需要跟服务器端定好接口,然后自己模拟数据进行返回。
我们可以使用OkHttp框架中的Interceptor(OkHttp中的Interceptor分为 Application Interceptor 和 Network Interceptor , 本文中的Interceptor均指Application Interceptor)对网络请求进行拦截,并返回模拟数据。

OkHttp Interceptor


如图,OkHttp Interceptor 可以对 Request 和 Response 进行处理。

利用这一机制,我们可以对 Request 进行拦截并将模拟数据填充于 Response 中并返回上层,从而达到模拟数据的目的。

以下为模拟知乎日报数据

// 创建Interceptorpublic class FakeApiInterceptor implements Interceptor {    @Override    public Response intercept(Chain chain) throws IOException {        Response response;        LogUtils.error(chain.request().url().toString());        // demo 知乎日报        if(chain.request().url().toString()                .equals("http://news-at.zhihu.com/api/4/news/latest")) {            String json = "太长了就不放上来了";            response = new Response.Builder()                    .code(200)                    .addHeader("Content-Type", "application/json")                    .body(ResponseBody.create(MediaType.parse("application/json"), json))                    .message(json)                    .request(chain.request())                    .protocol(Protocol.HTTP_2)                    .build();        }        // do nothing        else {            response = chain.proceed(chain.request());        }        return response;    }}// 创建OkHttpClient对象    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()            // 设置返回模拟数据Interceptor            .addInterceptor(fakeApiInterceptor)            // time out            .connectTimeout(20, TimeUnit.SECONDS)            .readTimeout(10, TimeUnit.SECONDS)            // 失败重连            .retryOnConnectionFailure(true)            .build();// 结合RetrofitRetrofit retrofit = new Retrofit.Builder()                .baseUrl("your url")                .client(okHttpClient)                .build();

参考链接:http://chaosleong.github.io/2017/01/23/okhttp-interceptor-server-mock/

0 0
原创粉丝点击