HttpClient send get Post interface request
/*** Post *@paramURL Post Address *@paramdata Post namevaluepair[] *@returnparameters of the response*/ Public Staticstring Post (string url,namevaluepair[] data) {---------------get contains no data but URL String response= ""; HttpClient HttpClient=NewHttpClient (); Postmethod Postmethod=Newpostmethod (URL); //Set Request EncodingPostmethod.getparams (). Setparameter (Httpmethodparams.http_content_charset, "GBK"); Postmethod.setrequestbody (data); ---------------------------------get does not have this step--------//set Request Header header parametersPostmethod.setrequestheader ("UserId", "57601095"); Postmethod.setrequestheader ("Usersession", "57601095"); Postmethod.setrequestheader ("Cityid", "31000"); intStatusCode = 0; Try{StatusCode=Httpclient.executemethod (Postmethod); } Catch(HttpException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Try { byte[] b=Postmethod.getresponsebody (); Response=NewString (b, "GBK"); } Catch(IOException e) {e.printstacktrace (); } postmethod.releaseconnection (); System.out.println ("Post response parameter:" +response); returnresponse; }
The following is a complete code with 301 redirects
/*** Post *@paramURL Post Address *@paramdata Post namevaluepair[] *@returnparameters of the response*/ Public Staticstring Post (string url,namevaluepair[] data) {------------------------get contains no data but URL String response = ""; HttpClient HttpClient=NewHttpClient (); Postmethod Postmethod=Newpostmethod (URL); //Set Request EncodingPostmethod.getparams (). Setparameter (Httpmethodparams.http_content_charset, "GBK");
Postmethod.setrequestbody (data);--------------------------------get without this step//set Request Header header parametersPostmethod.setrequestheader ("UserId", "57601095"); Postmethod.setrequestheader ("Usersession", "57601095"); Postmethod.setrequestheader ("Cityid", "31000"); intStatusCode = 0; Try{StatusCode=Httpclient.executemethod (Postmethod); } Catch(HttpException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } //301, 302 redirect if(StatusCode = = httpstatus.sc_moved_permanently | | statusCode = =httpstatus.sc_moved_temporarily) {Header Locationheader= Postmethod.getresponseheader ("Location"); String Location=NULL; if(Locationheader! =NULL) { location=Locationheader.getvalue (); System.out.println (REDIRECT Jump page: "+Location ); Response= post (Location,data);//re-request with the page after the jump. }Else{System.err.println ("Location is null."); } }Else{System.out.println (Postmethod.getstatusline ()); Try { byte[] b=Postmethod.getresponsebody (); Response=NewString (b, "GBK"); } Catch(IOException e) {e.printstacktrace (); } postmethod.releaseconnection (); } System.out.println ("Post response parameter:" +response); returnresponse; }
HttpClient Send Get,post Interface request