Android cookie rejected Solution

Source: Internet
Author: User

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");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.