Android网络请求优化

学习自trinea大神还有一些另外的文章


分析工具

1.Android内置的profile(monitor)

不仅可以看网络,还可以看内存,cpu

2.提供弱网的工具,测试弱网;还有wifi情况

3.截获网络包,进行分析


url

一般是用域名直接请求的,虽然local dns会缓存,但是最好还是能用其他的方式

1.直接请求ip

2.http dns


4大策略

1.提前取

2.分优先级,比如你要拿数据来更新UI,这个优先级需要高一点;比如你要点赞,你可以先UI显示了,再去进行一个post

3.打包,比如点赞,用户可能会瞎操作,不断点赞,取消赞,你可以在这个页面退出后,进行一个打包;打包的场景很多,最重要的原因是keep-alive机制,不打包=浪费资源(打包还可以节省电量)

4.错峰,不是非要100个请求在同一时间进行的,你的网络会在一瞬间被阻塞,完全可以分批,10个10个来。


压缩body

服务器传gzip的body给你,okhttp会自动解析的,前提是你不指定accepte-encoding

okhttp gzip压缩request body

(官方源码)

 /** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
  static class GzipRequestInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
      Request originalRequest = chain.request();
      if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
        return chain.proceed(originalRequest);
      }




      Request compressedRequest = originalRequest.newBuilder()
          .header("Content-Encoding", "gzip")
          .method(originalRequest.method(), gzip(originalRequest.body()))
          .build();
      return chain.proceed(compressedRequest);
    }




    private RequestBody gzip(final RequestBody body) {
      return new RequestBody() {
        @Override public MediaType contentType() {
          return body.contentType();
        }




        @Override public long contentLength() {
          return -1; // We don't know the compressed length in advance!
        }




        @Override public void writeTo(BufferedSink sink) throws IOException {
          BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
          body.writeTo(gzipSink);
          gzipSink.close();
        }
      };

    }


压缩header

spdy算法:deflate

http2.0算法:hpack

http1.0和1.1不能压缩,不过可以手动做缓存,相同header用密文id表示


精简文本格式

二进制protobuf

使用json的时候,合并多个对象的field为一个list,这样可以省去多余的field名


精简图片格式

大图用webp取代jpg,再不用webp就out啦!

小图用svg取代png


增量更新

多用于版本升级,服务端bsdiff,客户端bspatch


缓存

强制expire,cache control

对比modified,etag


大文件

缓存

断点续传

多连接


JobScheduler

监听系统,休眠,充电,wifi做不同的措施。比如wifi时自动下载一些东西


先UI,后数据的场景

IdHandler拿真正UI显示时机,先显示IO缓存数据

点赞

猜你喜欢

转载自blog.csdn.net/qq_36523667/article/details/80017475