Code:
- Using the httpurlconnection object, we can send request parameters to the network.
- String requesturl = "http: // localhost: 8080/itcast/contanctmanage. Do ";
- Map <string, string> requestparams = new hashmap <string, string> ();
- Requestparams. Put ("Age", "12 ");
- Requestparams. Put ("name", "China ");
- Stringbuilder Params = new stringbuilder ();
- For (Map. Entry <string, string> entry: requestparams. entryset ()){
- Params. append (entry. getkey ());
- Params. append ("= ");
- Params. append (urlencoder. encode (entry. getvalue (), "UTF-8 "));
- Params. append ("&");
- }
- If (Params. Length ()> 0) Params. deletecharat (Params. Length ()-1 );
- Byte [] DATA = Params. tostring (). getbytes ();
- URL realurl = new URL (requesturl );
- Httpurlconnection conn = (httpurlconnection) realurl. openconnection ();
- Conn. setdooutput (true); // The output must be allowed when a POST request is sent.
- Conn. setusecaches (false); // No cache is used.
- Conn. setrequestmethod ("Post ");
- Conn. setrequestproperty ("connection", "keep-alive"); // maintain a persistent connection
- Conn. setrequestproperty ("charset", "UTF-8 ");
- Conn. setrequestproperty ("Content-Length", String. valueof (data. Length ));
- Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded ");
- Dataoutputstream outstream = new dataoutputstream (conn. getoutputstream ());
- Outstream. Write (data );
- Outstream. Flush ();
- If (conn. getresponsecode () = 200 ){
- String result = readasstring (conn. getinputstream (), "UTF-8 ");
- Outstream. Close ();
- System. Out. println (result );
- }
216; MSO-Char-wrap: 1; MSO-kinsoku-overflow: 1'> 111%; visibility: hidden "> left: 43.5%; text-align: Left; font-family: wingdings; font-size: 70% "> L