添加cookie以改装2请求 [英] Add cookies to retrofit 2 request

查看:60
本文介绍了添加cookie以改装2请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加带有改良版2.0的Cookie.如果我理解正确,cookies-与标题相同.必须添加此Cookie:

I need to add cookies with retrofit 2.0. If i understand correct, cookies - the same as headers. this cookies must be added:

private HashMap<String, String> cookies = new HashMap();
cookies.put("sessionid", "sessionId");
cookies.put("token", "token");

这与Jsoup lib一起使用:

this one work with Jsoup lib:

String json = Jsoup.connect(apiURL + "/link")
                    .cookies(cookies)
                    .ignoreHttpErrors(true)
                    .ignoreContentType(true)
                    .execute()
                    .body();

这是我的代码,带有改装请求:

here is my code with retrofit request:

@GET("link")
Call<CbGet> getData(@Header("sessionid") String sessionId, @Header("token") String token);

但这是行不通的... 我收到403错误代码,因此请求中没有Cookie ...

but it is doesn't work... i get 403 error code so there are no cookies in the request...

有什么主意吗?

推荐答案

首先:cookie与标头不同. Cookie是一个名为 Cookie 的特殊HTTP标头,其后是键和值对的列表(以;"分隔).像这样:

First of all: cookie is not the same as a header. Cookie is a special HTTP header named Cookie followed by list of the pairs of keys and values (separated by ";"). Something like:

Cookie: sessionid=sessionid; token=token

由于您不能在同一请求中设置多个Cookie标头您不能将两个 @Header 注释用于单独的值(示例中的 sessionid token ).我可以想到一种非常hacky 的解决方法:

Since you cannot set multiple Cookie headers in the same request you are not able to use two @Header annotations for separate values (sessionid and token in your sample). I can think of one very hacky workaround:

@GET("link")
Call<CbGet> getData(@Header("Cookie") String sessionIdAndToken);

您更改了在一个字符串中发送sessionId和token的方法.因此,在这种情况下,您应该事先手动生成Cookie字符串.在您的情况下,sessionIdAndToken String对象应等于"sessionid = here_goes_sessionid ; token = here_goes_token "

You change your method to send sessionId and token in one string. So in this case you should manually generate cookie string beforehand. In your case sessionIdAndToken String object should be equal to "sessionid=here_goes_sessionid; token=here_goes_token"

适当的解决方案是通过添加 OkHttp (Retrofit用于进行基础http调用的库)来设置Cookie的此处.

The proper solution is to set cookies by adding OkHttp's (that is library Retrofit uses for making underlying http calls) request interceptor. You can see solution or adding custom headers here.

这篇关于添加cookie以改装2请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆