Java uses httpurlconnection and httpclient to simulate get and post requests separately and to manipulate cookies

Source: Internet
Author: User

1. Using HttpURLConnection

        Public Staticstring Getjsonbyurl (String base_url) {string URL=Base_url; StringBuilder JSON=NewStringBuilder (); String result= ""; Try{URL u=Newurl (URL); HttpURLConnection UC=(HttpURLConnection) u.openconnection (); Uc.setrequestmethod ("GET"); //Uc.setrequestmethod ("POST");                /*String cookieval =uc.getheaderfield ("Set-cookie");                Gets session String Jsessionid = (cookieval.substring ("0,cookieval.indexof ("; "))); Uc.setrequestproperty ("Cookie", jsessionid);//Set Session*/BufferedReader BD=NewBufferedReader (NewInputStreamReader (Uc.getinputstream (), "GBK")); String s=NULL;  while((S=bd.readline ())! =NULL) {json.append (s);            } bd.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } result=json.tostring (); returnresult; }

2. Using HttpClient

(1) Get

     Public Staticstring getjsonbyget (string url) {string s= ""; //closeablehttpclient httpclient = Httpclients.createdefault ();Defaulthttpclient httpclient =NewDefaulthttpclient (NewPoolingclientconnectionmanager ()); HttpGet HttpGet=Newhttpget (URL); Closeablehttpresponse Response=NULL; Httpentity Entity=NULL; Try{Response=Httpclient.execute (HttpGet); Entity=response.getentity (); /*Cookiestore Cookiestore = Httpclient.getcookiestore ();//access to Cookies Httpclient.setcoo Kiestore (Cookiestore);//Set Cookies*/s= Entityutils.tostring (Entity, "UTF-8"); } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{httpclient.close (); }                 returns; }    

(POST)

    Public Staticstring getjsonbypost (string url) {defaulthttpclient httpclient=NewDefaulthttpclient (NewPoolingclientconnectionmanager ()); //closeablehttpclient httpclient = Httpclients.createdefault (); HttpPost HttpPost =Newhttppost (URL); Closeablehttpresponse Response=NULL; Httpentity Entity=NULL; String s= ""; Try{Response=Httpclient.execute (HttpPost); Entity=response.getentity (); S= Entityutils.tostring (Entity, "UTF-8"); } Catch(clientprotocolexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }finally{httpclient.close (); }        returns; } 

The location of cookies and cookies is based on different interfaces.

The above method is to put the parameters of the interface, before calling the method is well-equipped, as a URL incoming. Processing can also be done inside the corresponding method of the call.

1. Using HttpURLConnection

     Public Static byte[] getjsonbyurl (string url, string params)throwsexception{URL url=Newurl (URL); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setrequestmethod ("POST");//         //Conn.setconnecttimeout (10000);//        //conn.setreadtimeout (+);//Conn.setdooutput (true);//         byte[] Bypes =params.tostring (). GetBytes (); Conn.getoutputstream (). write (bypes);//Input ParametersInputStream instream=Conn.getinputstream (); returnStreamtool.readinputstream (instream); }

There are many ways to deal with parameters, you can append (), you can do it yourself +, different parameters, different methods overload

2. Using HttpClient

Java uses httpurlconnection and httpclient to simulate get and post requests separately and to manipulate cookies

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.