OkHttp相关使用和设置缓存

本文详细介绍了OkHttp网络请求库的使用方法,包括其优点、请求和响应的封装、请求的构建过程、OkHttpClient的配置及使用、响应的处理方式,并提供了统一请求头处理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、优点:
  • 支持HTTP/2 协议,允许连接到同一个主机地址的所有请求共享Socket。这必然会提高请求效率。
  • 在HTTP/2协议不可用的情况下,通过连接池减少请求的延迟。
  • GZip透明压缩减少传输的数据包大小。
  • 响应缓存,避免同一个重复的网络请求。
二、请求和响应相关要素:
  • Request类封装客户端发送的请求,包括请求的url,请求方法method(主要是GET和POST方法)、请求头header以及请求体requestBody;
  • Response类封装了服务器响应的数据,包括code、message、body、header等。
  • OkHttpClient负责发送请求Request并通过同步或者异步的方式返回服务器的响应Response,就好比是一个浏览器。
三、请求Request:
1、设置header:
addHeader(String name, String value)  //可以添加多个值,不移除已有的
header(String name, String value) //设置唯一的name和value,如果有值,将值更新为新的
headers(Headers headers) //其他header被移除,只添加这一个header
removeHeader(String name) //移除头部的某个值
2、设置tag:
设置tag可以用来取消这一请求。如果未指定tag或者tag为null,那么这个request本身就会当做是一个tag用来被取消请求。
3、设置cacheControl:
替换name是"Cache-Control"的header。如果cacheControl是空的话就会移除请求头中name是"Cache-Control"的header。
4、请求体:RequestBody:
  • String类型
  • Stream流类型
  • File文件类型
  • Form表单形式的key-value类型
  • 类似Html文件上传表单的复杂请求体类型(多块请求)。

(1)创建String类型的请求体
public static RequestBody create(MediaType contentType, String content)
例:
String postBody = "";
Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
        .build();

(2)创建文件类型的请求体
public static RequestBody create(final MediaType contentType, final File file)
例:
File file = new File("README.md");
equest request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();
(3)创建流类型的请求体
对应的是name为Content-Type的header  
public abstract MediaType contentType();  
//这个BufferedSink位于Okio包下,提供高效的写入。  
public abstract void writeTo(BufferedSink sink) throws IOException;  
//在写入的时候可以传递内容的大小,如果不知道就返回-1即可。  
public long contentLength() throws IOException {  return -1;}
例:
RequestBody requestBody = new RequestBody() {
       @Override
        public MediaType contentType() {
             return MEDIA_TYPE_MARKDOWN;
        }

        @Override
         public void writeTo(BufferedSink sink) throws IOException {
              sink.writeUtf8("Numbers\n");
              sink.writeUtf8("-------\n");
              for (int i = 2; i <= 997; i++) {
                     sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
               }
           }

          private String factor(int n) {
                for (int i = 2; i < n; i++) {
                     int x = n / i;
                     if (x * i == n) return factor(x) + " × " + i;
                 }
                return Integer.toString(n);
                }
};

Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(requestBody)
        .build();

(4)FormBody表单类型请求体:添加key-value的形式

//采用OkHttp默认的编码

public Builder add(String name, String value) 

//采用用户要求的编码
public Builder addEncoded(String name, String value)
例:
RequestBody formBody = new FormBody.Builder()
                        .add("search", "Jurassic Park")
                        .build();
  Request request = new Request.Builder()
                        .url("https://en.wikipedia.org/w/index.php")
                        .post(formBody)
                        .build();

(5)分块MultipartBody:可以由多个请求体组成
MIME类型:
  public static final MediaType MIXED = MediaType.parse("multipart/mixed");
  public static final MediaType ALTERNATIVE = MediaType.parse("multipart/alternative");
  public static final MediaType DIGEST = MediaType.parse("multipart/digest");
  public static final MediaType PARALLEL = MediaType.parse("multipart/parallel”);

  //设置MIME类型,如MIXED(默认的)
    public Builder setType(MediaType type) {}

  //添加请求体
    public Builder addPart(RequestBody body) {
      return addPart(Part.create(body));
    }

  //添加包含header的请求体
    public Builder addPart(Headers headers, RequestBody body) {
      return addPart(Part.create(headers, body));
    }

    //请求体添加表单
    public Builder addFormDataPart(String name, String value) {
      return addPart(Part.createFormData(name, value));
    }

    //请求体中包含文件
    public Builder addFormDataPart(String name, String filename, RequestBody body) {
      return addPart(Part.createFormData(name, filename, body));
    }

    //添加自己定义的part
    public Builder addPart(Part part) {
      if (part == null) throw new NullPointerException("part == null");
      parts.add(part);
      return this;
    }
例:
RequestBody requestBody = new MultipartBody.Builder()
         .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
         RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();

 Request request = new Request.Builder()
         .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
         .url("https://api.imgur.com/3/image")
         .post(requestBody)
         .build();
四、OkHttpClient:
OkHttpClient采用建造者模式,通过Builder可以配置连接超时时间、读写时间,是否缓存、是否重连,还可以设置各种拦截器interceptor等。
请求同一个主机最大并发是5,所有的并发最大是64。
OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(60, TimeUnit.SECONDS)//连接超时时间
        .readTimeout(60, TimeUnit.SECONDS)//读的时间
        .writeTimeout(60, TimeUnit.SECONDS)//写的时间
        .build();
1、同步请求:会堵塞当前线程 execute()
response = client.newCall(request).execute();
2、异步请求:另一个线程中返回结果 enqueue()
client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              //处理错误的回调
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
              //处理正确的回调
            }
        });
3、请求取消 : Call.cancel()

五、Response:
可以通过Response的body得到一个ResponseBody读取。如果采用ResponseBody的string()方法会一次性把数据读取到内存中,如果数据超过1MB可能会报内存溢出,所以对于超过1MB的数据,建议采用流的方式去读取,如ResponseBody的byteStream()方法。
六、统一请求头的处理:
1、Log:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BasicConfig.DEBUG?HttpLoggingInterceptor.Level.BODY
        :HttpLoggingInterceptor.Level.NONE);
//BasicConfig.DEBUG:用来控制是否显示log 

2、请求头统一加入token
使用拦截器,拦截请求并加入请求头token
3、设置网络缓存:

有网:

不需要缓存:Cache-Control: no-cache或Cache-Control: max-age=0

在线缓存:先显示数据,在请求。Cache-Control: public, max-age=30000

注:可以通过一次网络请求的时间判断,在线缓存所需时间很短。

(1)针对单个请求设置缓存
 @Headers("Cache-Control: public, max-age=时间秒数")
 @GET("weilu/test")
 Observable<Test> getData();
(2)通过拦截器统一设置缓存方式
public class BaseIntercepter implements Interceptor {
    private Context mContext;
    //缓存有效期
    private static final long CACHE_STALE_SEC = 60 * 60 * 24 * 2;
    private String token;
    public BaseIntercepter(Context context) {
        mContext = context;
    }

    public void setToken(String token){
        this.token = token;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        LogUtil.e("net","网络:"+NetUtil.isConnected(mContext));
        if (!NetUtil.isConnected(mContext)){
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
        request = request.newBuilder().header("token",token).build(); //加入token
        Response originalResponse = chain.proceed(request);

        if (NetUtil.isConnected(mContext)){
            //有网的直接读取接口上@Headers的配置,实现某个请求的在线缓存
            String cacheControl = request.cacheControl().toString();
            //有网的时候统一处理缓存,将其超时时间这是为0:不需要缓存
            //String cacheControl="Cache-Control:public,max-age=0"
            return originalResponse.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")//清除头信息,如果服务器不支付回返回干扰信息,不清除没法生效
                    .build();
        }else{
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + CACHE_STALE_SEC)
                    .build();
        }
    }
}

(3)设置拦截器
 //设置缓存文件地址
            File cacheFile = new File(MyApplication.getInstance().getApplicationContext().getCacheDir().getAbsolutePath(),"response");
            //设置缓存大小

            mOkHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(logging) //拦截器
                    .cache(new Cache(cacheFile,1024*1024*100))
                    .addNetworkInterceptor(intercepter) //在线缓存
                    .addInterceptor(intercepter) //离线缓存
                    .connectTimeout(60*1000, TimeUnit.MILLISECONDS)
                    .build();

注:只是想实现在线缓存,那么可以只添加网络拦截器,如果只想实现离线缓存,可以使用只添加应用拦截器。


相关学习链接:http://blog.youkuaiyun.com/lmj623565791/article/details/47911083
http://blog.youkuaiyun.com/jdsjlzx/article/details/51482603


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值