PackageStep1;ImportOrg.apache.commons.httpclient.Cookie;Importorg.apache.commons.httpclient.HttpClient;ImportOrg.apache.commons.httpclient.NameValuePair;ImportOrg.apache.commons.httpclient.cookie.CookiePolicy;ImportOrg.apache.commons.httpclient.methods.GetMethod;ImportOrg.apache.commons.httpclient.methods.PostMethod;/*** * @ClassName: Httplogin * @Description: Java gets cookie emulation login via HttpClient *@authorZeze * @date November 10, 2015 PM 4:18:08 **/ Public classHttplogin { Public Static voidMain (string[] args) {//Login UrlString loginurl = "http://passport.mop.com/?targetUrl=http://hi.mop.com/?&g=1447141423230&loginCheck= Unlogined "; //URLs to be accessed after loginString Dataurl = "http://hi.mop.com/?"; HttpClient HttpClient=NewHttpClient (); //analog Login, according to the actual server-side requirements of the use of Post or Get request modePostmethod Postmethod =NewPostmethod (loginurl); //set the required information, user name and password when logging innamevaluepair[] data = {NewNamevaluepair ("LoginName", "chzeze123"),NewNamevaluepair ("loginpasswd", "* *") }; Postmethod.setrequestbody (data); Try { //set HttpClient to receive cookies, using the same policy as the browserhttpclient.getparams (). Setcookiepolicy (cookiepolicy.browser_compatibility); intStatuscode=Httpclient.executemethod (Postmethod); //access to cookies after landingcookie[] Cookies =httpclient.getstate (). GetCookies (); StringBuffer tmpcookies=NewStringBuffer (); for(Cookie c:cookies) {tmpcookies.append (c.tostring ()+ ";"); System.out.println ("Cookies =" +c.tostring ()); } if(statuscode==302) {//REDIRECT to a new URLSYSTEM.OUT.PRINTLN ("Emulation login succeeded"); //the operation after logging inGetMethod GetMethod =NewGetMethod (Dataurl); //Use the previous cookie as a pass for each visit to the URL you need to authorizeGetmethod.setrequestheader ("Cookie", tmpcookies.tostring ()); //You can also set more requests after the data by Postmethod/getmethod//For example, where Referer from, UA like search engines will be the name of who they are, except for unscrupulous search enginesPostmethod.setrequestheader ("Referer", "http://passport.mop.com/"); Postmethod.setrequestheader ("User-agent", "mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/31.0.1650.63 safari/537.36 "); Httpclient.executemethod (GetMethod); //print out the return data and verify the successString Text =getmethod.getresponsebodyasstring (); System.out.println (text); } Else{System.out.println ("Login Failed"); } } Catch(Exception e) {e.printstacktrace (); } }}
Java acquires cookie impersonation login via HttpClient