流行框架:OkHttp配置

拦截器(.addInterceptor())

在请求的过程中会执行一次拦截器中的interceptor方法,此时的请求还未发给服务器。那么可以在interceptor方法中对请求进行修饰,比如,不管是什么接口发起的请求,服务器希望每个请求带上当前的平台、应用的版本号等请求头。

public class InterceptorUnitTest {

    private static final String TAG = "InterceptorUnitTest";

    @Test
    public void interceptor() {
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @NonNull
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                // 创建和之前请求的request对象一样的Builder对象,然后在此基础上加上其它内容。
                Request request = chain.request().newBuilder()
                        .addHeader("os","Android")
                        .addHeader("version", BuildConfig.VERSION_NAME)
                        .build();

                // 向服务器发送新的请求
                Response response = chain.proceed(request);
                return response;
            }
        }).build();

        Request request = new Request.Builder().url("https://www.httpbin.org/get").build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

缓存(cache)

默认情况下,OkHttp的缓存是关闭状态,需要我们开启。步骤如下:

  1. 让OkHttpClient的构建者调用cache方法。

  2. 配置cache方法,只需要通过new Cache()。

  3. 为Cache的构造方法传递参数。

    file:保存缓存的文件位置。

    size:文件的最大大小,如果缓存大小以及超过了文件的大小,那么就会请求当前文件中的内容再存缓存。

其余步骤不变,就是网络请求,具体代码如下:

public class InterceptorUnitTest {

    private static final String TAG = "InterceptorUnitTest";

    @Test
    public void interceptor() {
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(new Cache(new File("C:\\Users\\杨小亮\\Desktop"),1024*1024))
                .addInterceptor(new Interceptor() {
            @NonNull
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                // 创建和之前请求的request对象一样的Builder对象,然后在此基础上加上其它内容。
                Request request = chain.request().newBuilder()
                        .addHeader("os","Android")
                        .addHeader("version", BuildConfig.VERSION_NAME)
                        .build();

                // 向服务器发送新的请求
                Response response = chain.proceed(request);
                return response;
            }
        }).build();

        Request request = new Request.Builder().url("https://www.httpbin.org/get").build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Cookie

Cookie是为了辨别用户身份、进行会话跟踪而存储在用户本地终端上的数据。

使用步骤:

  1. 调用cookieJar方法,配置cookieJar方法。

  2. 传入已经实现了的CookieJar接口。

    new CookieJar() {
        @Override
        public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
            /**
            * 服务器的cookie数据封装成List集合后通过回调接口返回给我们
            * 我们在这个方法中需要做的是将cookie数据保存的本地
            */
    	}
    
        @NonNull
        @Override
        public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
            /**
            * httpUrl是我们请求的服务器的url,我们需要判断当前请求的url和httpUrl是否相等
            * 相等我们就返回刚刚保存好的cookie List集合
            */
            return null;
        }
    }
    

具体代码:

public class CookieUnitTest {

    Map<String,List<Cookie>> cookies = new HashMap<>();

    @Test
    public void name() {
        OkHttpClient client = new OkHttpClient.Builder().cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
                cookies.put(httpUrl.host(),list);
            }

            @NonNull
            @Override
            public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
                List<Cookie> list = cookies.get(httpUrl.host());
                return list == null ? new ArrayList<>() : list;
            }
        }).build();

        FormBody formBody = new FormBody.Builder().add("username", "18146614162")
                .add("password", "yxl18679937350")
                .build();
        Request request = new Request.Builder()
                .url("https://www.wanandroid.com/user/login")
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        request = new Request.Builder().url("https://www.wanandroid.com/lg/collect/list/0/json").build();
        call = client.newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值