• 流行框架: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();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    缓存(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();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    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;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19

    具体代码:

    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();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
  • 相关阅读:
    linux安装MySQL8.0,密码修改权限配置等常规操作详解
    Could not find resource src/config/dataConfig.xml错误
    使用Pega进行一个简单的RPA程序开发
    Spark 环境安装与案例演示
    猿创征文|HCIE-Security Day49:AC准入控制SACG
    螺杆支撑座的这些特点,你知道吗?
    关于 Eclipse 的一场 “三角关系”
    Redis-Sentinel高可用架构学习
    C++:CRTP(Curiously Recurring Template Pattern 奇异递归模板)
    在线录音工具分享,总有一款适合你!
  • 原文地址:https://blog.csdn.net/qq_46653910/article/details/125565771