1, through GET request backstage, notice Tomcat encoding set to Utf-8; <connector connectiontimeout= "20000" port= "8080" protocol= "http/1.1" redirectport= "8443" URIEncoding= "UTF-8"/ >
/*** Send a GET request*/ Public Static voidget () {closeablehttpclient httpclient=Httpclients.createdefault (); Try { //first put the parameters in the list, and then URL code the parameterslist<basicnamevaluepair> params =NewLinkedlist<basicnamevaluepair>(); Params.add (NewBasicnamevaluepair ("Get", "Get request hahaha")); //encode the parameterString param = Urlencodedutils.format (params, "UTF-8"); //Create a httpget. HttpGet HttpGet =NewHttpGet ("http://localhost:8080/HttpServleTest.html?") +param); //executes a GET request. Closeablehttpresponse response =Httpclient.execute (HttpGet); Try { //Get response Entityhttpentity entity =response.getentity (); //Print response status codeSystem.out.println (Response.getstatusline (). Getstatuscode ()); if(Entity! =NULL) { //Print Response ContentSystem.out.println ("Response content:" + entityutils.tostring (Entity, "UTF-8")); } } finally{response.close (); } } Catch(Exception e) {e.printstacktrace (); } finally { //Close the connection and release the resource Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); } } }
2.post Request
/*** Send post*/ Public Static voidpost () {//creates a default HttpClient instance. Closeablehttpclient httpclient =Httpclients.createdefault (); //Create HttpPostHttpPost HttpPost =NewHttpPost ("http://localhost:8080/HttpServleTest.html"); //To create a parameter queueList<namevaluepair> Formparams =NewArraylist<namevaluepair>(); Formparams.add (NewBasicnamevaluepair ("Post", "POST request ha haha")); Urlencodedformentity uefentity; Try{uefentity=NewUrlencodedformentity (Formparams, "UTF-8"); Httppost.setentity (uefentity); Closeablehttpresponse Response=Httpclient.execute (HttpPost); Try{httpentity entity=response.getentity (); if(Entity! =NULL) {System.out.println ("Response content:" + entityutils.tostring (Entity, "UTF-8"))); } } finally{response.close (); } } Catch(Exception e) {e.printstacktrace (); } finally { //Close the connection and release the resource Try{httpclient.close (); } Catch(IOException e) {e.printstacktrace (); } } }
3, the background service program and this case code:
Simple use of httpclient