Http Communication for Android-5. Problems Encountered during development and android Problems
Http Communication for Android-5. Problems Encountered during development
Tags (separated by spaces): unclassified
This section introduces:
Okay, I haven't updated my blog here for a long time. It's not just that pig is lazy. It's actually busy with other things. This section should have explained how to encapsulate Http requests with pull fit. However, last week, I encountered two problems when using the basic HttpClient and HttpURLConnection for the project. After several days of struggle, I still felt that it was necessary to mark the project, they are the Cookie issue of the Http request and the PUT request issue sent by the server. That's right, it's "PUT", not GET or POST!
1. Cookie Problems
Speaking of this Cookie, we need to first understand something conceptual: Session and Cookie.
1)Let's take an example to illustrate this process:
Pig enters the account password, logs on to the school's educational administration system, and then successfully accesses the course list information. If Chrome is used, press F12 to enter the Development Mode: on the Resources page, we can see our Cookies:
Click it to view the saved content, including the name, value, domain in which the cookie is located, and the path in which the cookie is located (Asp.net). The default value is/, which is the root directory; expiration time; Cookie size:
Check that our request header contains a Cookie field!
Well, now we can clear the Cookie (or wait a few minutes) and then visit the following link:
At this time, the page automatically jumps back to the login page! Of course, some other websites may pop up a dialog box saying "Login timeout" and other things!
2)Well, this is the process for logging on to Http and accessing the relevant page after login:
Generally, when logging on to the server, the server returns a Cookie through the Set-Cookie response header. the browser saves the Cookie by default. This Cookie will be carried when you access the relevant page in the future, use the Cookie request header to complete the access. If no Cookie exists or the Cookie expires, the system prompts the user not to log on. The login times out and the access needs to be logged on!
3)We use HttpClient and HttpURLConnection to simulate this process. After logging in, we get the cookie and send the request with it:
HttpURLConnection:
Obtain Cookie:Conn. getHeaderField ("Set-Cookie ");
Cookie contained in the request:Conn. setRequestProperty ("Cookie", cookie );
In HttpClient:
A little more complex, you need to use an HttpResponse:
HttpResponse loginResponse = new defaulthttpclient(cmd.exe cute (getLogin );
Obtain Cookie:Cookie = loginResponse. getFirstHeader ("Set-Cookie"). getValue ();
Cookie contained in the request:HttpPost. setHeader ("Cookie", cookie );
Okay, the above is how HttpURLConnection and HttpClient bring cookies when getting and requesting them!
In addition, I had to worry about the problem for a few days: When I made a request, the log on the server had never been logged on. Later I realized that the log on the server did not process the request header. Okay, then the server keeps talking about my problems .... Drunk, and also discussed another compromise solution in the tangle process, "URL rewriting" is to use a session id, add one more after the basic request parameters for a Get request:
... & Sessionid = xxxxx, and then parse it on the server side. In the Post request, add a field to the form. The sample code is as follows:
Here we use a JSON string. When receiving a request, the server extracts the content in the session and then performs the following query ~
4)Finally, the difference between Session callback and Cookie is that Cookie is only a form of Session mechanism. We can also use other methods as a unique identifier of the client, such as the above "URL rewriting"
2. Processing of Put requests:
Put requests may be a bit unfamiliar to many friends. After all, we usually encounter GET and POST requests in many cases. At first, pig did not know, but later I found that it is similar to POST, and we only need to modify something on the basis of POST to use it! HttpClient also provides us with an HttpPut API. below, I will post the request code written by pig in my project:
Sample Code for HttpURLConnection to send a PUT request is as follows:
Public static String LoginByPut (Context mContext, String mobile, String password, int from, String devid, String version_name, int remember_me) {String resp = ""; try {HttpURLConnection conn = (HttpURLConnection) new URL (LOGIN_URL ). openConnection (); conn. setRequestMethod ("PUT"); conn. setreadtimeouts (5000); conn. setConnectTimeout (5000); conn. setDoOutput (true); conn. setDoInput (true); conn. setUseCach Es (false ); string data = "mobile =" + mobile + "& password =" + password + "& from =" + from + "& devid =" + "devid" + "& version_name = "+" version_name "+" & remember_me = "+ remember_me ;; // obtain the output stream: OutputStreamWriter writer = new OutputStreamWriter (conn. getOutputStream (); writer. write (data); writer. flush (); writer. close (); // get the expected Stream object: InputStream in = conn. getInputStream (); BufferedReader reader = new B UfferedReader (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 "";}
Use HttpPut to send a Put request:
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() == 200) { 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 relatively simple. In fact, the core is how to obtain cookies and bring our cookies when sending requests. Of course, some companies may not use Http Session to identify users, instead, we use the oAuth protocol, which will be used by companies for further research. We also talk about how to write Put requests! Well, see the next section ~
Reprinted please indicate the source:Coder-pigThank you. Please do not use them for commercial purposes. infringement is required ~