2019独角兽企业重金招聘Python工程师标准>>>

台风海马来深圳了,下面的虽然是英文,但是感觉比中文更容易让人看懂

Add Request Headers

Adding HTTP request headers is a good practice to add information for API requests. A common example is authorization using the Authorization header field. If you need the header field including its value on almost every request, you can use an interceptor to add this piece of information. This way, you don’t need to add the @Header annotation to every endpoint declaration.

OkHttp interceptors offer two ways to add header fields and values. You can either override existing headers with the same key or just add them without checking if there is another header key-value-pair already existing. We’ll walk you through both of them in the following paragraphs.

How to Override Headers

Intercepting HTTP requests with the help of OkHttp interceptors allows you to manipulate the actual request and apply your customization. The request builder has a .header(key, val) method which will add your defined header to the request. If there is already an existing header with the same key identifier, this method will override the previously defined value.

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {  @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {Request original = chain.request();// Request customization: add request headersRequest.Builder requestBuilder = original.newBuilder().header("Authorization", "auth-value"); // <-- this is the important lineRequest request = requestBuilder.build();return chain.proceed(request);}
});OkHttpClient client = httpClient.build();
```Retrofit, and especially OkHttp, allow you to add multiple headers with the same key. The .header method will replace all existing headers with the defined key identifier. Within the code snippet above, every Authorization header (if multiple have been defined already) will be updated and their previous value will be replaced with auth-value.# How to Not Override Headers
There are situations where multiple headers with the same name are used. Actually, we’re only aware of one specific example from practise: the Cache-Control header. The HTTP RFC2616 specifies that multiple header values with the same name are allowed if they can be stated as a comma-separated list.That means,
```
Cache-Control: no-cache
Cache-Control: no-store
```
is the same as
```
Cache-Control: no-cache, no-store
```
Using Retrofit 2 and an OkHttp interceptor, you can add multiple request headers with the same key. The method you need to use is .addHeader.The following example will add the Cache-Control headers from the example above:```
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {  @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {Request original = chain.request();// Request customization: add request headersRequest.Builder requestBuilder = original.newBuilder().addHeader("Cache-Control", "no-cache").addHeader("Cache-Control", "no-store");Request request = requestBuilder.build();return chain.proceed(request);}
});OkHttpClient client = httpClient.build();
```
# Take Away
Notice the small but mighty difference:- .header(key, val): will override preexisting headers identified by key
- .addHeader(key, val): will add the header and don’t override preexisting onesMake sure you’re using the appropriate method to achieve your desired request results.# Outlook
This post walked you through the different methods on how to add request headers using OkHttp’s request interceptors. Customizing the request and adding request header enable a simple and effective way to pass data with every request. This method will result in much cleaner code than adding header fields with the [@Header](https://my.oschina.net/header) annotation for every request.

转载于:https://my.oschina.net/zengliubao/blog/761424

Retrofit2/OkHttp 重写覆盖headers 与 不重写覆盖Headers相关推荐

  1. js函数重写php,深入讲解js覆盖原有方法 提供重写方法

    如果你做了一个编辑器,里面有提供一些光标离开事件等,最好使用此方法来操作,因为当他人使用你的编辑器时,也许要用到编辑器提供的事件方法处理些事情,其中部分事件需要根据特殊要求进行重写,因此,出现这种情况 ...

  2. 为什么重写equals方法必须要重写hashCode方法

    为什么重写equals方法必须要重写hashCode方法 ​ 了解这个问题之前我们得需要知道hashCode的作用.equals方法和hashCode方法都是Object类中的基础方法,用来判断两个对 ...

  3. Android使用RxJava+Retrofit2+Okhttp+MVP练习的APP

    Android使用RxJava+Retrofit2+Okhttp+MVP练习的APP 项目截图 这是我的目录结构 五步使用RxJava+Retrofit2+Okhttp+RxCache 第一步:导包 ...

  4. 重写equals方法时必须重写hashcode方法吗

    重写equals方法时必须重写hashcode 有规范: 1,当obj1.equals(obj2) 为 true 时,obj1.hashCode() == obj2.hashCode() 2,当obj ...

  5. why在重写equals时还必须重写hashcode方法

    首先我们先来看下String类的源码:可以发现String是重写了Object类的equals方法的,并且也重写了hashcode方法 public boolean equals(Object anO ...

  6. java equals重写原则_java中为何重写equals时必须重写hashCode方法详解

    前言 大家都知道,equals和hashcode是java.lang.Object类的两个重要的方法,在实际应用中常常需要重写这两个方法,但至于为什么重写这两个方法很多人都搞不明白. 在上一篇博文Ja ...

  7. php重写地址,php url地址重写

    地址重写: urlRewrite: 就是:  1. 将php的地址index.php不写只写Action模块和function方法, 或者 2. php地址转变成html地址, 就是一种假的html, ...

  8. 建议重写equals方法时也一并重写hashCode方法

    Object类中有这样一段说明,意思是建议我们equals方法和hashCode方法,或者一起重写,或者一起不重写,以维护hashCode的常规协定. 什么叫hashCode的常规协定呢? 我的理解就 ...

  9. java -为什么重写equals(),还需要重写hashCode()?

    1.先post这两个方法的基本定义: equals()的定义: 浅谈Java中的equals和==(转) hashCode()的定义: java中hashCode()方法的作用 Java中hashCo ...

  10. 为什么重写equals方法时必须重写hashcode方法

    文章目录 1. == 与 equals的区别 2. 重写equals() 3. 为什么重写equals方法时必须重写hashcode方法? 3.1 Hash算法 3.2 HashCode() 相关文章 ...

最新文章

  1. 2021中国大学排名发布:北京大学连续14年位居榜首
  2. leetcode 滴滴_一个菜逼程序媛的求职历程(秋招已拿阿里、网易、滴滴等校招offer)...
  3. 复习知识点:UITableView和UICollectionView的常用属性
  4. BZOJ1787 [Ahoi2008]Meet 紧急集合 LCA
  5. [渝粤教育] 西北大学 数据结构 参考 资料
  6. oracle数据块调用存储过程,VC调用存储过程的通用方法(ORACLE篇)
  7. mysql limit分页知乎_头发一天天的掉,你知道MySQL的Limit有性能问题吗?
  8. CentOS 7.4 64位 .tar.bz2 解压
  9. ctfmon.exe开机无法自动启动
  10. windows下载android源码
  11. mac版百度网盘客户端
  12. VGA接口、DVI接口、HDMI接口
  13. 位运算:【leedcode:只出现一次的数字】
  14. 【NOIP2016普及组】复赛——魔法阵
  15. 【论文翻译和解释(2)】LOF:Identifying Density-Based Local Outliers论文精读
  16. 由浅入深!大牛耗时一年最佳总结,让你的app体验更丝滑!3面直接拿到offer
  17. “宅经济”催化下的泛娱乐行业,未来将引爆哪些增长点?
  18. 前端如何实现一个滚动的文本字幕
  19. php 单词拼写检查,拼写检查 · phpstorm手册 · 看云
  20. Wireshark 抓取 iphone 测试机的数据包

热门文章

  1. 计算机专业 操作系统,计算机操作系统
  2. 巨杉内核笔记(一)| SequoiaDB 会话(session)简介
  3. 大数据量生成工具源代码(Delphi)
  4. 覃超:从湘西到Facebook,硅谷只是技术人生的一小站
  5. mysql表去掉回车、换行
  6. Webwork 学习之路【02】前端OGNL试练
  7. JUnit测试框架的使用经验分享
  8. Rational Rose 下载安装
  9. FastDfs上传图片时报错configparser.NoOptionError: No option ‘connect_timeout‘ in section: ‘__config__‘
  10. superset各种数据库连接地址(持续更新中)