我家伙,我正在使用改装,我想知道如何透明地处理会话cookie.
为此,我扩展了给定的ApacheClient,并在自定义调用ApacheClient.execute(HttpClient,HttpUriRequest)中使用了一个CookieStore:
为此,我扩展了给定的ApacheClient,并在自定义调用ApacheClient.execute(HttpClient,HttpUriRequest)中使用了一个CookieStore:
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扩展)?
解决方法
从API 9开始,您可以使用java.net.CookieManager,并可以设置系统范围的Cookie处理程序:
CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cookieManager);
是的,Apache Http客户端使用自己的cookie处理机制.但是不应该是问题,因为从API 9开始HttpURLConnection是推荐的HTTP客户端.如果您使用Square Square的Retrofit,您也可能喜欢他们的OkHttp lib – 具有很多有用功能的自定义URLConnection实现.