本文介绍了使用带有 Cookie 持久性的改造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我正在使用改造,我想知道如何透明地处理会话 cookie.为此,我扩展了给定的 ApacheClient 并在对 ApacheClient.execute(HttpClient, HttpUriRequest) 的自定义调用中使用了 CookieStore:

I guys, I'm using retrofit and I wonder how to transparently handle the session cookie.For that I extend the given ApacheClient and use a CookieStore in the custom call to ApacheClient.execute(HttpClient, HttpUriRequest) :

Client client = new ApacheClient() {
    final CookieStore cookieStore = new BasicCookieStore();
    @Override
    protected HttpResponse execute(HttpClient client, HttpUriRequest request) throws IOException {
        // BasicHttpContext is not thread safe
        // CookieStore is thread safe
        BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        return client.execute(request, httpContext);
    }
};

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(API_URL)
    .setClient(client)
    .build();

是否有更好的方法使用内置的改造 API(没有 HttpClient 扩展)来做到这一点?

Is there a better way to do this with the build-in retrofit API (with no HttpClient extension) ?

推荐答案

从 API 9 开始,你有 java.net.CookieManager 并且可以像这样设置系统范围的 cookie 处理程序:

Starting from API 9 you have java.net.CookieManager and can set system-wide cookie handler like this:

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);

是的,Apache Http 客户端使用自己的 cookie 处理机制.但这应该不是问题,因为从 API 9 HttpURLConnection 开始是推荐的 HTTP 客户端.如果您使用 Square 的 Retrofit,您可能还会喜欢他们的 OkHttp lib - 具有许多有用功能的自定义 URLConnection 实现.

Yes, Apache Http client uses its own cookie-handling mechanism. But it should not be the problem because starting from API 9 HttpURLConnection is recommended HTTP client.If you use Retrofit from Square you may also like their OkHttp lib - custom URLConnection implementation with lots of useful capabilities.

这篇关于使用带有 Cookie 持久性的改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:27