通过改造与C​​ookie持久性 [英] using retrofit with Cookie persistence

查看:168
本文介绍了通过改造与C​​ookie持久性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的家伙,我使用的是改造,我不知道如何透明地处理会话cookie。 为此我向给定的ApacheClient并使用CookieStore的在自定义调用ApacheClient.execute(HttpClient的,HttpUriRequest):

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客户端。 如果从广场使用改造你可能还喜欢自己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.

这篇关于通过改造与C​​ookie持久性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆