将cookie添加到客户端请求OkHttp [英] Add cookie to client request OkHttp

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

问题描述

所以我开始使用Okhttp 3,并且网络上的大多数示例都谈论较旧的版本

So i started using Okhttp 3 and most of the examples on the web talk about older versions

我需要向OkHttp客户端请求添加一个cookie,如何使用OkHttp 3来完成?

I need to add a cookie to the OkHttp client requests, how is it done with OkHttp 3?

就我而言,我只是想将其静态添加到客户端调用中,而不从服务器接收它

In my case i simply want to statically add it to client calls without receiving it from the server

推荐答案

您可以通过以下两种方式进行此操作:

There are 2 ways you can do this:

OkHttpClient client = new OkHttpClient().newBuilder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        final ArrayList<Cookie> oneCookie = new ArrayList<>(1);
                        oneCookie.add(createNonPersistentCookie());
                        return oneCookie;
                    }
                })
                .build();
...

public static Cookie createNonPersistentCookie() {
        return new Cookie.Builder()
                .domain("publicobject.com")
                .path("/")
                .name("cookie-name")
                .value("cookie-value")
                .httpOnly()
                .secure()
                .build();
    }

或者简单地

OkHttpClient client = new OkHttpClient().newBuilder()
        .addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                final Request original = chain.request();

                final Request authorized = original.newBuilder()
                        .addHeader("Cookie", "cookie-name=cookie-value")
                        .build();

                return chain.proceed(authorized);
            }
        })
        .build();

我觉得第二个建议就是您所需要的.

I have a feeling that the second suggestion is what you need.

您可以找到此处是一个有效的示例.

You can find here a working example.

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

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