Android-communication with WEB interactions in the same Session
Both Session, Cookie, and Session are used to save the status information of the client. They are all used to solve the problem of HTTP stateless. Session can be implemented using cookies or URL write-back. Cookie and Session have the following obvious differences: 1) Cookie stores the status on the client, and Session stores the status on the server; 2) cookies are small pieces of text stored by the server on the local machine and are sent to the same server as each request. The network server uses the HTTP header to send cookies to the client. On the client terminal, the browser parses these cookies and saves them as a local file. Then, it automatically uploads these cookies to any requests on the same server. 3) The Session is for each user. The value of the variable is stored on the server, and a sessionID is used to differentiate the session variables of different users, this value is returned to the server when the user's browser accesses it. When the customer disables the cookie, this value may also be set to get to return to the server; 4) for security: when you access a site that uses sessions and create a cookie on your machine, we recommend that you make the session mechanism on the server more secure. because it does not read the information stored by the customer. Session mechanism the Session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or a hash table may be used) to save information. When the program needs to create a session for a client request, the server first checks whether the client request contains a session id called the session id, if a session id is included, it indicates that a session has been created for this client before, and the server uses the session id to retrieve the session. (if the session id is not found, a new one may be created ), if the client request does not contain the session id, the client creates a session and generates a session id associated with the session. The session id value should be unique, the session id is returned to the client for saving in this response. Session implementation method 1) Cookie is used to implement the server to assign a unique JSESSIONID to each Session and send the Cookie to the client. When the client initiates a new request, the JSESSIONID will be carried in the Cookie header. In this way, the server can find the Session corresponding to this client. 2) using URL echo to implement URL write-back means that the server carries the JSESSIONID parameter in all links sent to the browser page, so that the client will send the JSESSIONID to the server after clicking any link. If you directly enter a url in the browser to request resources, the Session cannot match. Tomcat implements Session by using both Cookie and URL write-back mechanisms at the beginning. If the client supports Cookie, it will continue to use Cookie and stop using URL write-back. If the Cookie is disabled, URL write-back is always used. When jsp development processes the Session, remember to use response. encodeURL () for the link on the page (). Why is the interaction between the mobile phone and the server not implemented in the same session? The reason is very simple, that is, when the android mobile client accesses the web server, it does not set the sessionID for the http request header. When the web browser is used as the client to access the server, each time the client initiates a request, the sessionID: JSESSIONID in the interaction is carried in the Cookie header. The server obtains the corresponding Session based on the sessionID instead of re-creating a new Session (this Session is invalid ). Code (1) HttpURLConnection implements the copy Code URL = new url (requrl); HttpURLConnection con = (HttpURLConnection) URL. openConnection (); // obtain the sessionid. string cookieval = con. getHeaderField ("set-cookie"); String sessionid; if (cookieval! = Null) {sessionid = cookieval. substring (0, cookieval. indexOf (";");} // sessionid value format: JSESSIONID = AD5F5C9EEB16C71EC3725DBF209F6178. It is a key-value pair, not a single-value sending setting cookie: URL url = new URL ); httpURLConnectioncon = (HttpURLConnection) url. openConnection (); if (sessionid! = Null) {con. setRequestProperty ("cookie", sessionid);} copy the Code (2) HttpClient Singleton mode. Only one HttpClient object exists, the HttpClient object contains Cookie information. I used the singleton mode in the project: copy the code public class Client {private static HttpClient instance = null; private Client () {} public static HttpClient getInstance () {if (instance = null) {return instance = new DefaultHttpClient () ;}else {return instance ;}}} copy code copy code class myThread extends Thread {@ Override public void run () {try {HttpClient client = Client. getInstance (); String path = "http: // 192.168.1.4/zx X/test. php "; HttpPost httpPost = new HttpPost (path); List <NameValuePair> param = new ArrayList <NameValuePair> (); param. add (new BasicNameValuePair ("phonenumber", "18200000000"); httpPost. setEntity (new UrlEncodedFormEntity (param, "UTF-8"); HttpResponse response = client.exe cute (httpPost); int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). GetContent (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); String SysOut = new String (result, "UTF-8"); System. out. println (SysOut);} else {System. out. println ("code ----------->" + code + "") ;}} catch (Exception e) {e. printStackTrace ();} finally {} super. run () ;}} class myThread2 extends Thread {@ Override public void run () {try {HttpClient client = C Lient. getInstance (); String path = "http: // 192.168.1.4/zxx/test1.php"; HttpPost httpPost = new HttpPost (path ); list <NameValuePair> param = new ArrayList <NameValuePair> (); param. add (new BasicNameValuePair ("phonenumber", "18200000000"); HttpResponse response = client.exe cute (httpPost); int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). getC Ontent (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); String SysOut = new String (result, "UTF-8"); System. out. println (SysOut);} else {System. out. println ("code ----------->" + code + "") ;}} catch (Exception e) {e. printStackTrace ();} super. run () ;}} copy the code to use the same cookie to access the code. Code (3) SeesionId Url transfer is implemented by passing the SessionId value through the url to the page that you want to continue accessing in the same session. Php code: test2.php copy Code <? Phpsession_start (); header ("Content-type: text/html; charset = UTF-8"); if (isset ($ _ POST ['phonenumber']) {$ phone =$ _ POST ['phonenumber']; if (! Isset ($ _ SESSION ['phone']) {$ time = time () + 60*10*10; // 100 minutes $ _ SESSION ['phone'] = $ phone; echo session_id ();} else echo "POST phone already exist ";} if (isset ($ _ GET ['phonenumber']) {$ phone = $ _ GET ['phonenumber']; if (! Isset ($ _ SESSION ['phone']) {$ time = time () + 60*10*10; // 100 minutes $ _ SESSION ['phone'] = $ phone; echo session_id ();} else echo "GET phone already exist" ;}?> Copy the code test3.php to copy the code Session_id ($ _ GET ['id']); session_start (); header ("Content-type: text/html; charset = UTF-8 "); if (isset ($ _ POST ['phonenumber']) {$ phone =$ _ POST ['phonenumber']; echo "phone --> ". $ phone. "<br/>"; echo "_ SESSION [phone] --> ". $ _ SESSION ['phone']. "<br/>"; echo "SESSIONid ---> ". session_id (); if ($ _ SESSION ['phone'] = $ phone) echo "POST verification OK"; else echo "POST verification BAD ";} if (isset ($ _ GET ['phonenumber' ]) {$ Phone = $ _ GET ['phonenumber']; echo "phone --> ". $ phone. "<br/>"; echo "_ SESSION [phone] --> ". $ _ SESSION ['phone']. "<br/>"; echo "session_id ---> ". session_id (); if ($ _ SESSION ['phone'] = $ phone) echo "GET verify OK"; else echo "GET verify BAD ";} copy the code on Android (here we will test the new two HttpClient respectively): copy the code class myThread extends Thread {@ Override public void run () {try {client = new DefaultHttpClient (); String path = "h Ttp: // 192.168.1.4/zxx/test. php "; HttpPost httpPost = new HttpPost (path); List <NameValuePair> param = new ArrayList <NameValuePair> (); param. add (new BasicNameValuePair ("phonenumber", "18200000000"); httpPost. setEntity (new UrlEncodedFormEntity (param, "UTF-8"); HttpResponse response = client.exe cute (httpPost); int code = response. getStatusLine (). getStatusCode (); if (code = 200) {InputStream is = r Esponse. getEntity (). getContent (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); String SysOut = new String (result, "UTF-8"); System. out. println (SysOut); seesionId = SysOut;} else {System. out. println ("code ----------->" + code + "") ;}} catch (Exception e) {e. printStackTrace ();} finally {} super. run () ;}} class myThread2 extends Thread {@ Override public void run () {try {c Lient = new DefaultHttpClient (); String path = "http: // 192.168.1.4/zxx/test1.php? Id = "+ seesionId; HttpPost httpPost = new HttpPost (path); List <NameValuePair> param = new ArrayList <NameValuePair> (); param. add (new BasicNameValuePair ("phonenumber", "18200000000"); httpPost. setEntity (new UrlEncodedFormEntity (param, "UTF-8"); HttpResponse response = client.exe cute (httpPost); int code = response. getStatusLine (). getStatusCode (); if (code == 200) {InputStream is = response. getEntity (). GetContent (); ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = is. read (buffer ))! =-1) {baos. write (buffer, 0, len);} is. close (); baos. close (); byte [] result = baos. toByteArray (); String SysOut = new String (result, "UTF-8"); System. out. println (SysOut);} else {System. out. println ("code ----------->" + code + "") ;}} catch (Exception e) {e. printStackTrace ();} super. run () ;}} copy the code Session_id ($ _ GET ['id.