Android adds cookies to URLs

Source: Internet
Author: User

The other day, because the project needs to write a method to get data from the server through network connection, but the program needs to add cookies, because we have not studied cookies before (including web applications that have never been used or rarely used ),

It cannot be used at the moment .. As a result, Baidu Google discovered that cookiemanager should be used, and then the class can be operated!

Java code

  1. String getcookie (context ){
  2. Cookiemanager = cookiemanager. getinstance ();
  3. String cookie = cookiemanager. getcookie ("cookie ");
  4. If (cookie! = NULL ){
  5. Return cookie;
  6. } Else {
  7. Cookie = "XXX ";
  8. Cookiemanager. setcookie ("cookie", cookie );
  9. Return cookie;
  10. }
  11. }



We can see that we only need to set it here and then add it to our httpconnection.

Java code

  1. URL url = new URL (urlpath );
  2. Httpurlconnection httpurlconn = (httpurlconnection) URL. openconnection ();
  3. Httpurlconn. setrequestproperty ("cookie", getcookie (context ));



This seems to be correct .. That's what I understood at the time .. But unfortunately... An error is reported ..

Prompt createinstance () must be instance called before getinstance ()

Obviously, we must first generate this instance... The result shows that the API needs to be checked before getinstance ().
Java code

  1. Cookiesyncmanager. createinstance (context );



In this way, no errors will occur .. After createinstance, make sure that we have .. When using cookiemanager, WebKit uses the same cookiemanager and ensures thread synchronization ....

For this, see the source code of cookiesyncmanager. createinstance (context .....

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.