The Java analog POST request sends JSON in two ways, the first being the httpurlconnection sending the post request, and the second using the httpclient to simulate the post request,
Method One:
1 packagemain.utils;2 3 ImportJava.io.*;4 Importjava.net.HttpURLConnection;5 Importjava.net.URL;6 7 public classHttputiltest {8Log log =NewLog ( this. GetClass ());//Initialize the log class9 /**Ten * @ action using URLConnection one * @paramURL a * @paramParams - * @return - * @throwsIOException the */ - publicString Sendpost (string url,string Params)throwsioexception{ -OutputStreamWriter out =NULL; -BufferedReader reader =NULL; +String response= ""; - Try { +URL Httpurl =NULL;//the HTTP URL class uses this class to create a connection a //Create URL atHttpurl =NewURL (url); - //Establish a connection -HttpURLConnection conn =(httpurlconnection) httpurl.openconnection (); -Conn.setrequestmethod ("POST"); -Conn.setrequestproperty ("content-type", "application/json"); -Conn.setrequestproperty ("connection", "keep-alive"); inConn.setusecaches (false);//set do not cache -Conn.setinstancefollowredirects (true); toConn.setdooutput (true); +Conn.setdoinput (true); - Conn.connect (); the //POST Request *out =NewOutputStreamWriter ( $ Conn.getoutputstream ());Panax Notoginseng Out.write (Params); - Out.flush (); the //Read Response +Reader =NewBufferedReader (NewInputStreamReader ( a Conn.getinputstream ())); the String lines; + while((lines = Reader.readline ())! =NULL) { -Lines =NewString (lines.getbytes (), "utf-8"); $response+=lines; $ } - reader.close (); - //Disconnect Connection the Conn.disconnect (); - Wuyi log.info (response.tostring ()); the}Catch(Exception E) { -System.out.println ("send POST Request Exception!") "+e); wu e.printstacktrace (); - } about //Use the finally block to close the output stream, input stream $ finally{ - Try{ - if(out!=NULL){ - out.close (); a } + if(reader!=NULL){ the reader.close (); - } $ } the Catch(ioexception Ex) { the ex.printstacktrace (); the } the } - in returnresponse; the } the}
Method Two: using HttpClient to implement
1 //Post Request Method2 publicstring Sendpost (string url, string Data) {3String response =NULL;4Log.info ("url:" +url);5Log.info ("request:" +data);6 Try {7Closeablehttpclient httpclient =NULL;8Closeablehttpresponse HttpResponse =NULL;9 Try {TenHttpClient =Httpclients.createdefault (); oneHttpPost HttpPost =NewHttpPost (url); aStringentity stringentity =Newstringentity (data, -Contenttype.create ("text/json", "UTF-8")); - httppost.setentity (stringentity); theHttpResponse =Httpclient.execute (httppost); -Response =entityutils - . toString (httpresponse.getentity ()); -Log.info ("response:" +response); +}finally { - if(httpclient! =NULL) { + httpclient.close (); a } at if(httpresponse! =NULL) { - httpresponse.close (); - } - } -}Catch(Exception E) { - e.printstacktrace (); in } - returnresponse; to}
Java Analog POST request send JSON