如何使用Retrofit / OkHttpClient从响应中获取多个Set-Cookie标头?

时间:2015-12-09 14:23:51

标签: android cookies retrofit okhttp

我试图在Android上使用Retrofit / OkHttpClient进行身份验证调用。服务器用两个Set-Cookie头响应302,okHttp处理重定向。我找到了一些使用cookieManager获取这些cookie的技巧。但似乎cookieManager只读取一个Set-Cookie标头。

我在服务器响应标头中有这个:

Set-Cookie:first=1
Set-Cookie:second=2

这是我的cookieManager部分:

private static CookieManager cookieManager;
(...)
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setFollowSslRedirects(true);
okHttpClient.setAuthenticator(new NTLMAuthenticator(user, passwd, domain));

cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
okHttpClient.setCookieHandler(cookieManager);

处理Set-Cookie标头:

public void checkForSetCookies() {
    List<retrofit.client.Header> headerList = new ArrayList<>();
    List <HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    //List cookies has only one cookie:  first=1
    for (HttpCookie cookie : cookies) {
        retrofit.client.Header header = new retrofit.client.Header("Set-Cookie", cookie.toString());
        headerList.add(header);
    }

    if (headerList.size() > 0) {
        Commons.setLoginRetofitCookies(headerList);
    }
}

有没有办法强制cookieManager读取我的Set-Cookie标头?

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

我想我解决了这个问题。 CookieManager类正在解析响应标头列表:

List<HttpCookie> cookies = parseCookie(responseHeaders);

因此第二个cookie被覆盖。

我决定创建MyCookieManager内部类并覆盖其put方法,将cookie值放入字符串列表中。我调用super方法来进行所有标头验证。

class MyCookieManager extends CookieManager {

    @Override
    public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
        super.put(uri, stringListMap);
        if (stringListMap != null && stringListMap.get("Set-Cookie") != null)
            for (String cookieValue: stringListMap.get("Set-Cookie")) {
                cookiesStrings.add(cookieValue);
            }
    }
}

现在它可以正常工作:)

答案 1 :(得分:0)

获得多个&#34; Set-Cookie&#34;来自回复的标题:

 Call<LoginResponse> call = apiService.login(loginRequest);
    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            showProgress(false);
            if (response.body() != null) {

                LoginResponse loginResponse = response.body();
                //Get headers from response
                Headers headerResponse = response.headers();
                //convert header to Map
                Map<String, List<String>> headerMapList = headerResponse.toMultimap();
                //Get List of "Set-Cookie" from Map 
                List<String> allCookies = headerMapList.get("Set-Cookie");
                String cookieval = "";
                for (int i = 1; i < allCookies.size(); i++) {
                    allCookies.get(i);
                    //concat all cookies in cookieval.
                    cookieval = cookieval + allCookies.get(i);
                }
                //Save cookies value in Application class.
                ((AppConfig) getApplication()).setCookies(cookieval);

                ((AppConfig) getApplication()).setUserInfo(loginResponse);
                if (loginResponse.getStatus().equals("ok")) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    mAuthTask = true;
                    finish();
                } else {
                    mPasswordView.setError(getString(R.string.error_incorrect_password));
                    mPasswordView.requestFocus();
                }
            }
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Log.d(TAG, "onFailure: ");
            mAuthTask = false;
        }
    });

传递其他服务中的所有cookie(例如,注销服务)

 @Headers({"Content-Type: application/json"})
@POST("request/get/user/logout")
Call<LogoutResponse> logout(@Header("Cookie") String cookie);

在Api界面中添加此代码

现在拨打注销服务,如:

Call<LogoutResponse> call = apiService.logout(((AppConfig) getApplication()).getCookies());
    call.enqueue(new Callback<LogoutResponse>() {
        @Override
        public void onResponse(Call<LogoutResponse> call, Response<LogoutResponse> response) {
            if(response.body() != null){
                LogoutResponse logoutResponse = response.body();
                if (logoutResponse.getStatus().equals("ok")) {
                    finish();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            }
        }

        @Override
        public void onFailure(Call<LogoutResponse> call, Throwable t) {
            Log.d(TAG, "onFailure: ");
        }
    });

答案 2 :(得分:0)

You can write an extension function with Kotlin.

fun Headers.getCookies(): String? {
    var cookieString: String? = null
    this.toMultimap()["Set-Cookie"]?.forEach {
    cookieString += it
    }
    return cookieString
}

答案 3 :(得分:0)

您可以使用 response.headers().values("some_header") 获取标题的多个值

   val authCookies = mutableMapOf<String, String>()
   val response = restManager.login(AuthDto().apply {
            clientId = agent.clientId
            apiKey = "awesome_api_key"
        }).execute()
        response.headers().values("Set-Cookie").forEach {
            if (it.startsWith("auth=")) {
                authCookies["auth"] = it
            } else {
                authCookies["refresh"] = it
            }
        }