HttpURLConnection, HttpClient, and Session

Source: Internet
Author: User

Address: http://www.cnblogs.com/kross/p/3615695.html

 

I have never understood Session and cookies. I used HttpURLConnection and HttpClient to test what happened during login verification, I basically figured out the difference between the Session authentication Login Mechanism and the two classes.

Step 1: first write a login page and a content page locally (only after logging in. The code is roughly as follows:

Below isLogin. phpFor request login, PASS Parameters through post. If the login is successful, the session will be registered.

<? (['Username' = ['username' = ['Password' (= 'admin' & = 'admin' ['username'] = "<a href = 'content. php '> go to the website </a> "}"-1 "?> <Html> <body> <form action = "" method = "post"> <input type = "text" name = "username"/> <input type = "password" name = "password"/> <input type = "submit" name = "submit" value = "submit"/> </form> </body> 

Below isContent. phpWill verify the session, used as the website content page, login to see the correct content.

<? ((['username' "login ok" "not login"?>

Next, let's talk aboutHttpURLConnectionThis class uses this class to directly requestContent. phpPage, as expected, "-1" is returned ". If you use this class to requestLogin. phpAnd pass the correct parameters, it will show that the login is successful, and then use this class requestContent. phpIs still returned "-1", it is clear that HttpURLConnection does not record the status of our login, or the server knows the person who just logged in successfully, but this request content. php users still don't know each other. This indicates that each request of HttpURLConnection is independent, and is a new request, or each request is a new session ).

Then I used chrome to open the test webpage I wrote. I found that there was a sessionid in the same session under the same website.

This is the above thing. If a page is opened, the value of this SESSIONID will not change no matter how you refresh it or jump to another website under this server, however, if you turn off all the pages under the server and re-open such a page, the SESSIONID value will be re-generated.

 

Therefore, when HttpURLConnection is used, log on to login for the first time. php is a sessionid. the login is successful. The server remembers the situation where SESSIONID is A (assuming A is good), but then requests content. in php, SESSIONID Is Not A, and the server considers that you have not logged on, so it displays "-1 ". After understanding the problem, you only need to add the SESSIONID header to the HttpURLConnection request. The final code is as follows:

      String sessionId = ""     String request(String url) = ="Cookie", sessionId);    =  BufferedReader(= ""= "" ((line = br.readLine()) != = data +     String login(String url) = =        huc.setRequestMethod("POST"        StringBuffer params = "username=").append("admin").append("&").append("password=").append("admin"[] bytes =        String[] aaa = huc.getHeaderField("Set-Cookie").split(";"= aaa[0=  BufferedReader(= ""= "" ((line = br.readLine()) != = data +

 

The next step is to useHttpClientThe code is similar. After I perform the same experiment, the result is displayed directly. HttpClient automatically manages the Session, and the second request can be logged on without the need to manually set the Session.

  HttpClient client = =  String request(String url) = ==  BufferedReader(= ""= "" ((line = br.readLine()) != = data + String login(String url) =         ArrayList<NameValuePair> pa =  ArrayList<NameValuePair> BasicNameValuePair( "username", "admin" BasicNameValuePair( "password", "admin" UrlEncodedFormEntity(pa, "UTF-8"==  BufferedReader(= ""= "" ((line = br.readLine()) != = data +

In conclusion, the Session verification method is to generate a SESSIONID for each client in a Session. If a Session is successfully logged in, the server will record it, if the login fails or the new SESSIONID, the login cannot be verified. This is the basic situation for SESSION verification login.

Both HttpURLConnection and HttpClient can be used for network requests, but they are slightly different. Each request of HttpuRLConnection is a new session. If you need to verify the SESSIONID, you must manually set the Header, httpClient can intelligently manage sessions without manual settings. In fact, HttpClint is similar to a small browser in a program.

 

The biggest slot I think is that the methods for Setting post parameters for these two classes are both 2B and not convenient at all ......

 

In addition, HttpClient cannot send two requests at the same time. If a request is not completed or closed, another request is enabled immediately. A warning will be reported. Cut a picture.

 

So I have taken a comprehensive consideration and try to use HttpURLConnection in the future ......

 

Address: http://www.cnblogs.com/kross/p/3615695.html

Sina Weibo: http://weibo.com/KrossFord

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.