Android HTTP communication--5. Some problems encountered in the development
tags (space delimited): Uncategorized
Introduction to this section:
Well, for a long time not here to update the blog, not piglet lazy, in fact, is busy some other things, originally this section should be explained under the combination of retrofit to encapsulate the HTTP request, however, Last week in the use of basic httpclient and httpurlconnection to do the project encountered two problems, tangled for a few days, the pig still feel the need to mark, respectively, is the HTTP request of the cookie problem and like the server sent a put request problem, yes is " PUT "instead of Get or post!
1.Cookie problem
Speaking of this cookie, we need to know something conceptual: session and Cookie.
1) Let us first give you an example of this process:
The pig entered the account password after landing the school's educational system, and then access to the curriculum information successfully, and then if you are using chrome, press F12 to enter the development mode: come to the resources interface to see our cookies:
After the click we can see the contents of the content, by the name; value; the domain in which the cookie resides; the directory in which the cookie resides (path) is the root directory by default; the expiration time; Cookie size:
Look at our request. There's a cookie field in the header!
Well, now let's clear the cookie (or wait a few minutes) and then visit the following link:
At this time, the page unexpectedly jumped back to landing page! Of course some other sites may pop up a dialog box saying "login Timeout" or something like that!
2) Well, this is the process of landing in our HTTP and accessing the relevant pages after landing:
Usually the time to log in: The server through the Set-cookie response header, return a cookie, the browser default to save this cookie, subsequent visits to the relevant page will bring this cookie, through the cookie request header to complete the visit, If no cookie or cookie expires, the user is prompted not to log in, login timeout, access needs to login and other information!
3) and we use httpclient and httpurlconnection in fact that is the simulation of this process, landed after the cookie took it to send a request:
in HttpURLConnection:
Access to Cookies:Conn.getheaderfield ("Set-cookie");
Cookie on request:conn.setrequestproperty ("cookie", cookie);
In HttpClient:
Slightly more complex, to use to a httpresponse:
HttpResponse loginresponse = new Defaulthttpclient (). Execute (getlogin);
To obtain a cookie:cookie = Loginresponse.getfirstheader ("Set-cookie"). GetValue ();
Cookie on request:httppost.setheader ("cookie", cookie);
Okay, here's how httpurlconnection and httpclient get a cookie with the request!
There are also the author of a few days of the problem is that before making a request, the server log has been the user is not logged in, later only know that the service side of the people did not handle the request head, OK, and then the service also has been said that my problem .... drunk, and in the course of the tangle also discussed another compromise solution, " URL Rewrite ", is to use a session Id,get request, after the basic request parameters to add one more:
... &sessionid=xxxxx so, then he parses the server, and when the post requests, add a field to the form, with the following code example:
Here we use the form of a JSON string, when requested by the server to take out the contents of the session, and then make a query can ~
4) Finally, the difference between the session and the cookie, the cookie is only a form of the session mechanism, we can also use other means as a client's unique identity, such as the above "url rewrite"
2.Put Processing of requests:
Put request for a lot of friends may be a little strange, after all, we usually contact more cases are get and post, the beginning of the pig did not know, but later found and post is actually similar, and we just on the basis of post pity Dorado things can be used! And HttpClient also provides us with a Httpput API, below the pig's own project to write the request code it:
HttpURLConnection send the PUT request sample code as follows:
public static string Loginbyput (Context Mcontext, String Mobile, string password, int. from, String Devid, String ve rsion_name, int remember_me) {String resp = ""; try {HttpURLConnection conn = (httpurlconnection) new URL (Login_url). OpenConnection (); Conn.setrequestmethod ("PUT"); Conn.setreadtimeout (5000); Conn.setconnecttimeout (5000); Conn.setdooutput (TRUE); Conn.setdoinput (TRUE); Conn.setusecaches (FALSE); String data = "mobile=" + Mobile + "&password=" + password + "&from=" + from + "&devid=" + "Devid" + "&version_name=" + "Version_name" + "&remember_me=" + remember_me; ; Get output stream: outputstreamwriter writer = new OutputStreamWriter (Conn.getoutputstream ()); Writer.write (data); Writer.flush (); Writer.close (); Get the corresponding Stream object: InputStream in = Conn.getinputstream (); BufferedReader reader = new BufferedReader (New InputstreamreaDer (in)); StringBuilder response = new StringBuilder (); String Line; while (line = Reader.readline ())! = null) response.append (line); Sputils.put (Mcontext, "session", Conn.getheaderfield ("Set-cookie")); Resource release: In.close (); Returns the string log.e ("HEHE", response.tostring ()); return response.tostring (); } catch (Exception e) {e.printstacktrace (); } ; Return "";}
to send a put request using Httpput:
public static int Putactcode (string actcode, String licplate, Context mcontext) {int resp = 0; String cookie = (string) sputils.get (Mcontext, "session", ""); Httpput httpput = new Httpput (Putackcode_url); Httpput.setheader ("Cookie", cookie); try {list<namevaluepair> params = new arraylist<namevaluepair> (); Params.add (New Basicnamevaluepair ("Activation_code", Actcode)); Params.add (New Basicnamevaluepair ("License_plate", licplate)); Httpput.setentity (New urlencodedformentity (params, "UTF-8")); HttpResponse course_response = new Defaulthttpclient (). Execute (httpput); if (Course_response.getstatusline (). Getstatuscode () = = () {httpentity entity2 = course_response.getentity (); Jsonobject jobject = new Jsonobject (entityutils.tostring (Entity2)); RESP = Integer.parseint (jobject.getstring ("Status_code")); Return resp; }} catch (Exception e) {e.printstacktrace (); } return resp;}
3. Summary:
Well, the content is still relatively simple, in fact, the core is how to get cookies and send requests to bring our cookies, of course, some companies may not use the HTTP protocol session to identify users, but the use of the OAuth protocol, follow-up companies if the use of further research And said the next put request how to write! Well, I'll see you next day.
Reproduced please specify the source:Coder-pig, thank you, please do not use for commercial purposes, infringement must investigate ~
Android HTTP communication--5. Some problems encountered in the development