如何在Retrofit请求里添加Cookie

如何在Retrofit请求里添加Cookie,第1张

你可以自定义一个RequestIntercaptor:

String cookieKey = ...

String cookieValue = ...

RestAdapter adapter = new RestAdapter.Builder()

.setRequestInterceptor(new RequestInterceptor() {

@Override

public void intercept(RequestFacade request) {

// assuming `cookieKey` and `cookieValue` are not null

request.addHeader("Cookie", cookieKey + "=" + cookieValue)

}

})

.setServer("http://...")

.build()

YourService service = adapter.create(YourService.class)

从服务器读取cookies再交给cookie manager管理:

OkHttpClient client = new OkHttpClient()

CustomCookieManager manager = new CustomCookieManager()

client.setCookieHandler(manager)

RestAdapter adapter = new RestAdapter.Builder()

.setClient(new OkClient(client))

...

.build()

CustomeCookieManager如下:

public class CustomCookieManager extends CookieManager {

// The cookie key we're interested in.

private final String SESSION_KEY = "session-key"

/**

* Creates a new instance of this cookie manager accepting all cookies.

*/

public CustomCookieManager() {

super.setCookiePolicy(CookiePolicy.ACCEPT_ALL)

}

@Override

public void put(URI uri, Map<String, List<String>>responseHeaders) throws IOException {

super.put(uri, responseHeaders)

if (responseHeaders == null || responseHeaders.get(Constants.SET_COOKIE_KEY) == null) {

// No cookies in this response, simply return from this method.

return

}

// Yes, we've found cookies, inspect them for the key we're looking for.

for (String possibleSessionCookieValues : responseHeaders.get(Constants.SET_COOKIE_KEY)) {

if (possibleSessionCookieValues != null) {

for (String possibleSessionCookie : possibleSessionCookieValues.split("")) {

if (possibleSessionCookie.startsWith(SESSION_KEY) &&possibleSessionCookie.contains("=")) {

// We can safely get the index 1 of the array: we know it contains

// a '=' meaning it has at least 2 values after splitting.

String session = possibleSessionCookie.split("=")[1]

// store `session` somewhere

return

}

}

}

}

}

}

1、Retrofit创建

2、Retrofit实现Cookie自动化管理

3、Retrofit,Gson解析,请求返回的类型不统一,假如double返回的是null

4、请求参数日志打印

5、统一请求参数添加到请求头中

6、统一请求参数添加到请求body中

7、缓存的拦截器

8、BaseUrl动态切换

9、拦截指定接口,动态更改返回值便于测试

点击传送查看

点击传送查看

1.第一种办法,依赖第三方库

配置信息如下

2.第二种办法,拦截器拦截(个人推荐第二种,可控性高)

给大家推荐一个打印日志库,很漂亮的日志结构

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

用了一个博客中民间大神的拦截动态替换baseUrl方法有点问题,我暂时用了一种简单粗暴方法

上边的路径是我随便写的,post中写全路径,这个优先级最高,同时设置了baseUrl不受影响

给大家一个专门写动态替换baseUrl连接 传送门

有时候我们需要返回指定值测试,可能需要空或者null等,迫于无法修改服务器返回数据,也没必要让后台修改数据,所以引发一个问题,如果拦截返回内容并修改指定字段值

然后在httpClientBuilder中添加拦截


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/tougao/11360612.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存