Using Apache httpclient to simulate a student's personal information system

Source: Internet
Author: User

The educational system design of different schools should be different, this is only for my school. This article is mainly about as a pure small white even return code 302 do not understand how I step by step.

I'm going to use Java.

Because the analog login this piece has not been done before, simple Baidu, found the development of the corresponding package, such as HttpClient, the internet also has someone else do a good code upload, so first run someone else's code to try Bai, remember to need the jar package first good and import into the project, the following is someone else's code

Package Com.zb.util;import Java.io.bufferedreader;import Java.io.inputstream;import java.io.InputStreamReader; Import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.abstracthttpclient;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Java.text.simpledateformat;import Java.util.ArrayList;import Java.util.date;import Java.util.list;import Org.apache.http.cookie.cookie;public class PostData {HttpResponse HttpResponse; List<cookie> cookies; String result = ""; String data = "";p ublic void GetResult () {String URL = "http://210.38.137.101:9080/xsxt/xsxt.jsp";//sea Big HttpClient HTTPCLI ent = new Defaulthttpclient ();/* Establish an HTTP POST connection */httppost httppost = new HttPpost (URL); list<namevaluepair> params = new arraylist<namevaluepair> ();//user name Password Params.add (new Basicnamevaluepair (" UserId "," xxxx "));p Arams.add (New Basicnamevaluepair (" Userpass "," xxx ")), or//send HTTP Requesttry {//Emit HTTP request/* Added to HttpPost submitted content */httppost.setentity (new urlencodedformentity (params, "UTF-8"));//execute, get Httpresponsehttpresponse = Httpclient.execute (HttpPost);//If the status code is OKIF (Httpresponse.getstatusline (). Getstatuscode () = = 200) {//return value normal// Gets the Returned cookiecookies = ((abstracthttpclient) httpclient). Getcookiestore (). GetCookies (); /*string timestatus = "201011311229" + New SimpleDateFormat ("Mmddhhmmss"). Format (new Date ()); *///String kburl = "http:// 210.38.137.101/pls/wwwbks/xk. Courseview "////view HttpWatch in the corresponding urlstring Cjurl =" HTTP://210.38.137.101/PLS/WWWBKS/BKSCJCX.YXKC ";/* Set up httpget online */ HttpGet httpget = new HttpGet (cjurl); Httpget.setheader ("Cookie", "jsessionid=" + cookies.get (0). GetValue ()); Httpget.setheader ("Referer", "http://210.38.137.101:9080/xsxt/left.jsp")///Httpresponse.setheader ("user-agent",//"mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; trident/6.0) "); HttpResponse response2 = new Defaulthttpclient (). Execute (httpget);/* If the status code is a number of OK */system.out.println ("status=" + Response2.getstatusline (). Getstatuscode ()); if (Response2.getstatusline (). Getstatuscode () = = () {StringBuffer SB = New StringBuffer ();//Gets the response entity httpentity entity = response2.getentity (); InputStream is = Entity.getcontent (); BufferedReader br = new BufferedReader (new InputStreamReader (IS, "GB2312")),//is to read the source to be changed, the source format is GB2312, the Anyuan format read in, Then convert the source code to the desired encoding on the line while (data = Br.readline ()) = null) {sb.append (data);} result = Sb.tostring (); At this point, the result is the source code of our results html}} catch (Exception e) {e.printstacktrace ();} HttpClient Httpclient2 = new Defaulthttpclient (); SYSTEM.OUT.PRINTLN (data); SYSTEM.OUT.PRINTLN (result);} public static void Main (string[] args) {postdata PD = new PostData ();//Pd.postdata ();pd. GetResult ();}}


After all, the current small white, naturally, which has so easy to succeed, so began a long time to find problems and solve the problem of the process, the middle also stopped for a long period, there is no way to class many other things, after all, this is just an idea after school. I use the grab Bag tool is the Httpfox under the Firefox, this would like to use HttpWatch, Firefox can not use, because the next is the basic version, IE unexpectedly also can not use, the old hint to upgrade to profession version, temporarily no interest, make use of first, personal feel novice's focus is not a tool.

That's a little bit more nonsense. I went to the information system, just see what the post data past, yes, just stuid,pwd,

That should not ah, look at other people's code seems to be right, but there are still some areas of doubt, such as this sentence: Httpget.setheader ("Cookie", "jsessionid=" + cookies.get (0). GetValue ()); The first run is the error, what null pointer abnormal, do not understand the first thing alas ... Toss for a long time, catch the package of a look, look at each address, and constantly in the original code of various adjustments, such as the above this sentence deleted, ran up, but get the page text is, please enter the account password and so on is no login on the meaning. Look closely at the code can know is divided into two steps, the front is the beginning of the login, back run to the results of the page. Since the boarding is not boarded, then the main attack login this piece, but the post of all post, what, then did not understand the cookie, just think it is his title, after all kinds of Baidu, cookies are sent to the server after the service side returned to the client is a browser identity, This way you will only need to highlight your cookies after logging in to prove that you have logged in and can continue browsing. Then it shouldn't be a matter of cookies. Just a whim tried the next post address to the page login page, unexpectedly failed, to know the middle stop to do before it seems to have been using it is he ah, dizzy! So remind everyone, grab the bag to look at the post to which address, not you in which page address login, on the post to that, to my school, for example, after grasping the obvious login page is a combination of several modules together. Or not, then what happened, in the process of Baidu I saw the concept of redirection, that is, the service side returned 302, Qiao, as if to grab a packet, and I found in the post that the query string has a value

Many tests are dynamic, will not be related to them, in the catch of the package also found a related JS file, inside is a few functions, it seems to be related to his value, as well as the capture package to see the address of the post, is on the original basis added Jym2005=value, At this point I thought this was the redirect address .... If he gets it again, the ideal is always plump, and then began to study how to get this value, can get a long time and no results, Baidu to the query string things do not understand what is or has a relationship with this, I also Baidu how to directly get redirected address, tried the various methods on the Internet , there is no basis, can only follow the test Bai, can not be achieved will not change, but still found a can be used Httpresponse.getlastheader ("location"). GetValue (); I print out what it gets, and I find it's not really jym, But this thing login2.loginmessage, days, this is too far away, and then a flurry of blind, and finally, if careful attention to the above right to the second address of the picture save a lot of time, Login2.loginmessage is not get that URL, redirect this is post and then Get because I tried to open it directly with the second URL in the browser, the result is blank ... Yes, for a lap or a httpresponse.getlastheader ("location"). GetValue (); Complete test, unexpectedly can boarded up, now get out, Find Jym what and get login2.loginmessage between the two must be there is some kind of connection, the latter should not just a simple string, this can be studied later, as long as the log on, and then check the results of the curriculum is good to get, not much to say, in addition I get cookies worth the way more rigid, If there is a good way to thank the advice.

Package Test;import Java.io.bufferedreader;import Java.io.inputstream;import java.io.inputstreamreader;import Org.apache.http.header;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.abstracthttpclient;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.protocol.basichttpcontext;import Org.apache.http.protocol.executioncontext;import Java.util.arraylist;import Java.util.list;import org.apache.http.cookie.cookie;public class Test {HttpResponse HttpResponse; List<cookie> cookies; String result = "";  String cookie = ""; String data = "";p ublic void GetResult () {String URL = "http://";//Hithttpclient httpclient = new Defaulthttpclient ();/* Establish an HTTP POST connection */httppost httppost = new HttpPost (URL); list<namevaluepair> params = new arraylist<namevaluepair> ();//user name Password Params.add (new Basicnamevaluepair (" Stuid "," xxxx "));p Arams.add (" pwd "," xxxx "));//Send HTTP Requesttry {//Emit HTTP request/* Added to HttpPost submitted content */httppost.setentity (new urlencodedformentity (params, "UTF-8"));//execute, get Httpresponsehttpresponse = Httpclient.execute (HttpPost);//If the status code is 302 redirect if (Httpresponse.getstatusline (). Getstatuscode () = = 302) {// Gets the Returned cookiecookies = ((abstracthttpclient) httpclient). Getcookiestore (). GetCookies (); header[] headers = httpresponse.getallheaders (); Cookie=headers[4].getvalue (); cookie=cookie.substring (0,27);// System.out.println (cookie);  String Locationurl=httpresponse.getlastheader ("location"). GetValue (); /* Establish HttpGet online */httpget httpget = new HttpGet ("http://" +locationurl); Httpget.setheader ("Cookie", cookie); HttpResponse response2 = new Defaulthttpclient (). Execute (httpget);/* If the status code is a. OK */if (responSe2.getstatusline (). Getstatuscode () = = () {System.out.println ("Login Successful! "); HttpGet HttpGet1 = new HttpGet ("http://"), Httpget1.setheader ("cookie", cookie); HttpResponse response3 = new Defaulthttpclient (). Execute (HTTPGET1); StringBuffer sb = new StringBuffer (); httpentity entity = response3.getentity (); InputStream is = Entity.getcontent (); BufferedReader br = new BufferedReader (new InputStreamReader (IS, "GB2312") and while ((data = Br.readline ()) = null) {Sb.app End (data);} result = Sb.tostring (); In this case, result is our result of the HTML source code}elsesystem.out.println ("redirect Jump failed, Login failed!") ");} ELSE{SYSTEM.OUT.PRINTLN ("Login failed! ");}} catch (Exception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN (data); SYSTEM.OUT.PRINTLN (result);} public static void Main (string[] args) {test PD = new test ();pd. GetResult ();}}


Using Apache httpclient to simulate a student's personal information system

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.