Java – using cookie persistence improvement
•
Java
My guy, I'm using modification, and I want to know how to handle session cookies transparently
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();
Is there a better way to do this with the built-in modification API (no httpclient extension)?
Solution
Starting with API 9, you can use Java net. Cookie manager and can set system wide cookie handlers:
CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cookieManager);
Yes, the Apache HTTP client uses its own cookie handling mechanism But it should not be a problem, because httpurlconnection is the recommended HTTP client from API 9 If you use square square's Retro fit, you may also like their okhttp lib – a custom urlconnection implementation with many useful features
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码