0

以前,我使用 bash 脚本来执行以下操作

访问站点并将 cookie 保存在文件“/tmp/cookie-file”中

curl --cookie-jar /tmp/cookie-file https://www.some-site.com

下载/tmp/cookie-file的将如下所示

# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

.some-site.com     TRUE    /       FALSE   1564858012      B       6tbvhitdm98os&b=3&s=q2

然后,再次访问同一个站点,以及之前下载的 cookie 文件

curl --cookie /tmp/cookie-file https://www.some-site.com/some-api

现在,我想执行相同的操作。但是使用安卓。一直以来,我都在使用Retrofit图书馆。

我可以知道,在 中Retrofit,我们如何将 cookie 下载到临时文件中,并再次发出另一个 HTTP 请求以及之前下载的 cookie 文件?

4

2 回答 2

0

Retrofit 由 OKHttp 支持,OKHttp 接受请求的拦截器,因此您可以实现拦截以获取和添加 cookie,如下所示:https ://gist.github.com/tsuharesu/cbfd8f02d46498b01f1b

为了保持答案一致,我将复制上面的代码:

public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
            Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
        }

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

public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
              cookies.add(header);
            }

            Preferences.getDefaultPreferences().edit()
                .putStringSet(Preferences.PREF_COOKIES, cookies)
                .apply();
        }

        return originalResponse;
    }
}

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
clientBuilder.addInterceptor(new AddCookiesInterceptor());
clientBuilder.addInterceptor(new ReceivedCookiesInterceptor());

new Retrofit.Builder()
            .client(clientBuilder.build())
            .build();

要点已经将 cookie 保存在 SharedPreferences 中,我认为这也是您的最佳选择。如果您需要将 cookie 保存在文件中,请发表评论,我会更新答案。

于 2018-08-03T19:37:36.550 回答
0

您可以使用cookieManager.

添加此依赖项:

compile 'com.squareup.okhttp3:okhttp-urlconnection:3.6.0'

客户端生成器:

static OkHttpClient buildOkClientWithCookieManager() {
    CookieManager cookieHandler = new CookieManager();
    cookieHandler.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .cookieJar(new JavaNetCookieJar(cookieHandler));
    return builder.build();
}

在改造生成器中添加此客户端。

于 2018-08-04T05:14:03.467 回答