Package com.newflypig.demo;/** * uses the JDK's own httpurlconnection to send a POST request to the URL and output the response result * parameters are passed by stream and hardcoded to the format of the string "name=xxx" */ Import Java.io.bufferedreader;import Java.io.dataoutputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Java.net.urlencoder;public class SendPostDemo {public static void Main (string[] args) throws exception{string URLPath = new String ("Http://localhost:8080/Test1/HelloWorld"); String urlpath = new String ("Http://localhost:8080/Test1/HelloWorld?name= Tintin". GetBytes ("UTF-8")); String param= "Name=" +urlencoder.encode ("Ding Ding", "UTF-8");//Establish connection URL url=new url (urlpath); HttpURLConnection httpconn= (httpurlconnection) url.openconnection ();//Set parameter Httpconn.setdooutput (TRUE);// Output Httpconn.setdoinput (true) required;//input httpconn.setusecaches (false) required; Cache Httpconn.setrequestmethod ("POST") is not allowed; Set post mode connection//Set request Properties Httpconn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Httpconn.setrequestproperty ("Connection", "keep-alive");//Maintain longConnect the Httpconn.setrequestproperty ("Charset", "UTF-8");//Connect, or you can use the following httpconn.getoutputstream () without the plaintext connect will automatically connecthttpconn.connect ();//create an input stream, pass in the parameter to the URL that points to DataOutputStream Dos=new DataOutputStream ( Httpconn.getoutputstream ());d os.writebytes (param);d os.flush ();d os.close ();//Get response status int resultcode= Httpconn.getresponsecode (); if (Httpurlconnection.http_ok==resultcode) {stringbuffer sb=new StringBuffer (); String Readline=new string (); BufferedReader responsereader=new BufferedReader (New InputStreamReader (Httpconn.getinputstream (), "UTF-8"), while ( (Readline=responsereader.readline ())!=null) {sb.append (ReadLine). Append ("\ n");} Responsereader.close (); System.out.println (Sb.tostring ());}}}
Java uses httpurlconnection to send post data in the form of a outputstream stream
During the encoding process, the parameters are sent in the form of the string "Name=xxx"
Java sends post data using raw HttpURLConnection