HttpClient the cookie value returned after successful login to access the next page

Source: Internet
Author: User
Tags setcookie

Httpclient4.x can bring its own maintenance session functionality, as long as the same httpclient is used and the connection is not closed, you can use the same session to access other services that require login verification (see the "Performing a GET Request" section in the Testlogin () method).

If you need to use the httpclient pool, and you want to do a single logon session for multiple httpclient connections, you need to save the session information yourself. Because the client's session information is stored in a cookie (Jsessionid), only the cookies that are successfully returned by the login need to be copied to each httpclient for use. There are two ways to use cookies, either by using Cookiestore (see the Testcookiestore () method) or by using the Httpclientcontext context (see TestContext () method).

 Packagecom.sunbin.httpSession;Importjava.io.IOException;Importjava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Map;ImportJava.util.Map.Entry;ImportOrg.apache.http.HeaderIterator;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.ParseException;ImportOrg.apache.http.client.CookieStore;ImportOrg.apache.http.client.config.CookieSpecs;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;ImportOrg.apache.http.client.protocol.HttpClientContext;ImportOrg.apache.http.config.Registry;ImportOrg.apache.http.config.RegistryBuilder;ImportOrg.apache.http.cookie.CookieSpecProvider;ImportOrg.apache.http.impl.client.BasicCookieStore;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.HttpClients;ImportOrg.apache.http.impl.cookie.BasicClientCookie;Importorg.apache.http.impl.cookie.BestMatchSpecFactory;Importorg.apache.http.impl.cookie.BrowserCompatSpecFactory;ImportOrg.apache.http.message.BasicNameValuePair;Importorg.apache.http.util.EntityUtils;Importorg.junit.Test; Public classtesthttpclient {//Creating an Cookiestore instance  StaticCookiestore Cookiestore =NULL; StaticHttpclientcontext context =NULL; String loginurl= "Http://127.0.0.1:8080/CwlProClient/j_spring_security_check"; String Testurl= "Http://127.0.0.1:8080/CwlProClient/account/querySubAccount.action"; String Loginerrorurl= "Http://127.0.0.1:8080/CwlProClient/login/login.jsp"; @Test Public voidTestlogin ()throwsException {System.out.println ("----Testlogin"); // //Create Httpclientbuilder//Httpclientbuilder Httpclientbuilder = Httpclientbuilder.create (); // //HttpClient//closeablehttpclient client = Httpclientbuilder.build (); //Create a client directlyCloseablehttpclient client =Httpclients.createdefault (); HttpPost HttpPost=NewHttpPost (loginurl); Map Parametermap=NewHashMap (); Parametermap.put ("J_username", "sunb012"); Parametermap.put ("J_password", "sunb012"); Urlencodedformentity postentity=Newurlencodedformentity (GetParam (parametermap),"UTF-8");    Httppost.setentity (postentity); System.out.println ("Request Line:" +httppost.getrequestline ()); Try {      //perform a POST requestHttpResponse HttpResponse =Client.execute (HttpPost); String Location= Httpresponse.getfirstheader ("Location"). GetValue (); if(Location! =NULL&&Location.startswith (Loginerrorurl)) {System.out.println ("----LoginError");       } printresponse (HttpResponse); //perform a GET requestSYSTEM.OUT.PRINTLN ("----The same client"); HttpGet HttpGet=NewHttpGet (Testurl); System.out.println ("Request Line:" +httpget.getrequestline ()); HttpResponse httpResponse1=Client.execute (HttpGet);        Printresponse (HTTPRESPONSE1); //Cookie StoreSetcookiestore (HttpResponse); //ContextSetContext (); } Catch(IOException e) {e.printstacktrace (); } finally {      Try {        //close a stream and release resourcesClient.close (); } Catch(IOException e) {e.printstacktrace (); } }} @Test Public voidTestContext ()throwsException {System.out.println ("----TestContext"); //Use the context methodCloseablehttpclient client =Httpclients.createdefault (); HttpGet HttpGet=NewHttpGet (Testurl); System.out.println ("Request Line:" +httpget.getrequestline ()); Try {      //perform a GET requestHttpResponse HttpResponse =Client.execute (httpget, context); System.out.println ("Context Cookies:" +Context.getcookiestore (). GetCookies ());    Printresponse (HttpResponse); } Catch(IOException e) {e.printstacktrace (); } finally {      Try {        //close a stream and release resourcesClient.close (); } Catch(IOException e) {e.printstacktrace (); } }} @Test Public voidTestcookiestore ()throwsException {System.out.println ("----Testcookiestore"); //using the Cookiestore methodCloseablehttpclient client =Httpclients.custom (). Setdefaultcookiestore (Cookiestore). build (); HttpGet HttpGet=NewHttpGet (Testurl); System.out.println ("Request Line:" +httpget.getrequestline ()); Try {      //perform a GET requestHttpResponse HttpResponse =Client.execute (HttpGet); System.out.println ("Cookie Store:" +cookiestore.getcookies ());    Printresponse (HttpResponse); } Catch(IOException e) {e.printstacktrace (); } finally {      Try {        //close a stream and release resourcesClient.close (); } Catch(IOException e) {e.printstacktrace (); }    }  }    Public Static voidprintresponse (HttpResponse httpresponse)throwsParseException, IOException {//Get response message entityhttpentity entity =httpresponse.getentity (); //Response StatusSystem.out.println ("Status:" +httpresponse.getstatusline ()); System.out.println ("Headers:"); Headeriterator iterator=Httpresponse.headeriterator ();  while(Iterator.hasnext ()) {System.out.println ("\ T" +Iterator.next ()); }    //determine if the response entity is empty    if(Entity! =NULL) {String responsestring=entityutils.tostring (entity); System.out.println ("Response Length:" +responsestring.length ()); System.out.println ("Response content:" + responsestring.replace ("\ r \ n", "")); }  }    Public Static voidSetContext () {System.out.println ("----SetContext"); Context=httpclientcontext.create (); Registry<CookieSpecProvider> Registry =Registrybuilder.<CookieSpecProvider>Create (). Register (Cookiespecs.best_match,Newbestmatchspecfactory ()). Register (cookiespecs.browser_compatibility,Newbrowsercompatspecfactory ()). build ();    Context.setcookiespecregistry (registry);  Context.setcookiestore (Cookiestore); }    Public Static voidSetcookiestore (HttpResponse httpresponse) {System.out.println ("----Setcookiestore"); Cookiestore=NewBasiccookiestore (); //JsessionidString Setcookie = Httpresponse.getfirstheader ("Set-cookie"). GetValue (); String Jsessionid= Setcookie.substring ("jsessionid=". Length (), Setcookie.indexof (";")); System.out.println ("Jsessionid:" +Jsessionid); //Create a new cookieBasicclientcookie cookie =NewBasicclientcookie ("Jsessionid", Jsessionid); Cookie.setversion (0); Cookie.setdomain ("127.0.0.1"); Cookie.setpath ("/cwlproclient"); //Cookie.setattribute (clientcookie.version_attr, "0"); //Cookie.setattribute (clientcookie.domain_attr, "127.0.0.1"); //Cookie.setattribute (clientcookie.port_attr, "8080"); //Cookie.setattribute (clientcookie.path_attr, "/cwlproweb");Cookiestore.addcookie (cookie); }    Public StaticList<namevaluepair>GetParam (Map parametermap) {List<NameValuePair> param =NewArraylist<namevaluepair>(); Iterator it=Parametermap.entryset (). iterator ();  while(It.hasnext ()) {Entry Parmentry=(Entry) it.next (); Param.add (NewBasicnamevaluepair (String) Parmentry.getkey (), (String) parmentry.getvalue ()); }    returnparam; }}

HttpClient The cookie value returned after successful login to access next page

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.