In Android, when using httpclient of Apache for HTTP connection, if cookie is required, the general practice is:
// Create a local instance of cookie storecookieStore = new BasicCookieStore();// Bind custom cookie store to the local contextlocalContext = new BasicHttpContext();localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);// To perform http getHttpGet request = new HttpGet(url);HttpResponse response = new DefaultHttpClient().execute(request, localContext);if (response.getStatusLine().getStatusCode() == 200) {String result = EntityUtils.toString(response.getEntity());// log(result)}
In general, Cookie usage is okay, but now there are many large websites, and the login verification is in a different domain, which will lead to the problem that cookie cross-domain cannot be written. I found it difficult to find a solution after searching, and finally found it on stackoverflow. Java htmlunit-can't login to WordPress
In fact, Apache documents have already explained this problem. Please refer to the following section: Chapter 3. Http state management. The example is provided.
The method is to rewrite the cookie policy and set the custom policy for the HTTP client.
Mainly in:
CookieSpecFactory csf = new CookieSpecFactory() { public CookieSpec newInstance(HttpParams params) { return new BrowserCompatSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // Oh, I am easy } }; }};DefaultHttpClient httpclient = new DefaultHttpClient();httpclient.getCookieSpecs().register("easy", csf);httpclient.getParams().setParameter( ClientPNames.COOKIE_POLICY, "easy");