OkHttp CookieJar无法添加cookie来请求

时间:2017-10-12 20:52:11

标签: java cookies kotlin okhttp

我正在尝试使用CookieJar将已保存的身份验证Cookie添加到进一步的请求中。虽然获取正确的身份验证cookie并将其保存到jar中工作得很好,但在检查response.request().headers()时,cookie无处可寻。

我发现这个特别奇怪,因为我通过调试发现为请求调用loadForRequest()并返回正确的cookie。在Postman中使用完全相同的cookie伪造请求时,它会返回所需的结果(没有登录表单的页面)。

有人可以试着解释我错过的东西吗?

使用jar的类

class HTMLRoutes {
    var scheme = "https"
    var host = "www.mangaupdates.com"
    val cookieJar = MULoginCookieJar()
    var client = OkHttpClient.Builder()
            .cookieJar(cookieJar)
            .build()
/*Other code*/

private fun getHTMLFromUrl(url: HttpUrl): String {
        var request = Request.Builder()
                .url(url)
                .build()
        client.newCall(request).execute().use { response ->
        //Right before returning response the loadForRequest() method gets called in the MUCookieJar class
            if (response.isSuccessful) {
            //response.request.headers = ""
                if (response.body() != null) {
                    return response.body()!!.string()
                } else {
                    throw IOException("Response body is empty")
                }
            } else {
                throw IOException("Unexpected code" + response)
            }
        }
    }
}

我的cookiejar

class MULoginCookieJar : CookieJar {
    private var secureSessionCookie: Cookie? = null

    override fun saveFromResponse(url: HttpUrl?, cookies: MutableList<Cookie>?) {
        if (url != null && cookies != null) {
            if (url.pathSegments().size > 0 && url.pathSegments()[0] == "login.html") {
                for (cookie in cookies) {
                    if(cookie.name() == "secure_session") {
                        secureSessionCookie = cookie
                    }
                }
            }
        }
    }

    override fun loadForRequest(url: HttpUrl?): List<Cookie>? { // url = https://www.mangaupdates.com/series.html?id=14829
        if(url != null && url.pathSegments().size > 0 && url.pathSegments()[0] == "login.html") {
            return emptyList()
        }

        val cookies: List<Cookie> = if(secureSessionCookie==null) emptyList() else listOf(secureSessionCookie!!)
        return cookies // = ["secure_session=601bbc74; expires=Sun, 07 Oct 2018 20:45:24 GMT; domain=www.mangaupdates.com; path=/; secure; httponly"]
    }
}

非常感谢帮助。我已经很长时间潜伏了,但这是我第一次遇到这个问题。

1 个答案:

答案 0 :(得分:2)

我建议使用现有的cookie jar,而不是创建自己的。关于cookie的规则可能会变得很复杂。

template<typename T> class Foo {

    Foo(T* const t_contained) {

        // set up stuff
    }

    template<typename T_CONVERT_TO>
    FOO<T_CONVERT_TO> asFoo() {

        // assuming m_contained can convert to Foo<T_CONVERT_TO>'s m_contained
        // if not it'll complain, so you know asFoo can only be given covnertable values
        return Foo<T_CONVERT_TO>( m_contained );
    }
};

Foo<BarB> fooBarB;
Foo<BarA> fooBarA = fooBarB.asFoo<BarB>();

另外,为了帮助调试,您可以设置OkHttp debug logging with an interceptor

import okhttp3.JavaNetCookieJar;

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
JavaNetCookieJar cookieJar = new JavaNetCookieJar(cookieManager);

OkHttpClient client = new OkHttpClient.Builder().cookieJar(cookieJar).build();