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
- String getcookie (context ){
- Cookiemanager = cookiemanager. getinstance ();
- String cookie = cookiemanager. getcookie ("cookie ");
- If (cookie! = NULL ){
- Return cookie;
- } Else {
- Cookie = "XXX ";
- Cookiemanager. setcookie ("cookie", cookie );
- Return cookie;
- }
- }
We can see that we only need to set it here and then add it to our httpconnection.
Java code
- URL url = new URL (urlpath );
- Httpurlconnection httpurlconn = (httpurlconnection) URL. openconnection ();
- 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
- 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 .....