使用Retrofit将cookie作为文件下载,然后再次将cookie作为文件转发

时间:2018-08-03 19:04:26

标签: android retrofit2

以前,我使用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

现在,我想执行相同的操作。但是使用Android。一直以来,我都在使用Retrofit库。

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

2 个答案:

答案 0 :(得分: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保存到文件中,请发表评论,我会更新答案。

答案 1 :(得分:0)

您可以使用cookieManager来做到这一点。

添加此依赖项:

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

Client Builder:

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();
}

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