The Post method is a bit more complicated than the Get method, because the method needs to put the requested parameters in the body of the HTTP request, so the request body needs to be constructed.
Steps:
1. Construct the URL
URL url = new URL (PATH); 2. Setting Up a connection
HttpURLConnection connection = (httpurlconnection) url.openconnection (); Connection.setconnecttimeout (+); Connection.setdoinput (TRUE);//indicates that data is fetched from the server connection.setdooutput (TRUE);//indicates the byte size and length of writing data to the server//getting upload information Connection.setrequestmethod ("POST"); Whether to use cache Connection.setusecaches (false); The type that represents the set request body is the text type connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Connection.setrequestproperty ("Content-length", String.valueof (Mydata.length)); Connection.connect ();
3. Writing the request body
map<string, string> params = new hashmap<string, string> ();p arams.put ("username", "Lili");p Arams.put (" Password "," 123 "); StringBuffer buffer = new StringBuffer (); try {//writes the requested body to the body!! if (params! = Null&&!params.isempty ()) {//iterator for (map.entry<string, string> Entry:params.entrySet ( ) { buffer.append (Entry.getkey ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), encode)). Append ("&");} } System.out.println (buffer.tostring ()); Delete the last character & Buffer.deletecharat (Buffer.length ()-1) ; byte[] MyData = buffer.tostring (). GetBytes (); Get output stream, output data to server outputstream outputstream = Connection.getoutputstream (); Outputstream.write (mydata,0,mydata.length);
4. Read the return data and close the connection
Usually called a memory stream, written in memory bytearrayoutputstream outputstream = new Bytearrayoutputstream (); byte[] data = new Byte[1024];int len = 0 ; String result = "", if (inputstream! = null) {try {while (len = inputstream.read (data))!=-1) {data.tostring (); O Utputstream.write (data, 0, Len);} result is the result = new String (Outputstream.tobytearray (), encode) in the Dopost function set on the server side; Outputstream.flush ();
Here's the code: A simple demo accesses a self-built servlet:
Package com.http.post; Import Java.io.ByteArrayOutputStream; Import java.io.IOException; Import Java.io.InputStream; Import Java.io.OutputStream; Import java.io.UnsupportedEncodingException; Import java.net.HttpURLConnection; Import java.net.MalformedURLException; Import Java.net.URL; Import Java.net.URLEncoder; Import Java.util.HashMap; Import Java.util.Map; public class Httputils {private static String PATH = "Http://172.24.87.47:8088/myhttp/servlet/LoginAction"; private static URL URL; Public Httputils () {//TODO auto-generated constructor stub} static{try {ur L = new URL (PATH); } catch (Malformedurlexception e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * @param params fill in the parameters of the URL * @param encode byte encoding * @return */public static String sendpostmessage (map<string, string> params,string encode) { StringBuffer buffer = new StringBuffer (); try {//writes the principal of the request to the body!! if (params! = Null&&!params.isempty ()) {//iterator for (map.entry<string, string> E Ntry:params.entrySet ()) {Buffer.append (Entry.getkey ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), encode)). Append ("&"); }}//System.out.println (buffer.tostring ()); Delete the last character & Buffer.deletecharat (Buffer.length ()-1); byte[] MyData = buffer.tostring (). GetBytes (); HttpURLConnection connection = (httpurlconnection) url.openconnection (); Connection.setconnecttimeout (3000); Connection.setdoinput (TRUE);//indicates that data is obtained from the server Connection.setdooutput (TRUE);//The word that writes data to the server//obtains the upload information Section size and length Connection.setrequestmethod ("POST"); Whether to use cache connection.setusecaches (false); The type that represents the set request body is the text type Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded"); Connection.setrequestproperty ("Content-length", String.valueof (Mydata.length)); Connection.connect (); Connect, do not write also can ...?? Need to understand//get output stream, output data to server OutputStream OutputStream = Connection.getoutputstream (); Outputstream.write (mydata,0,mydata.length); Get the result of the server response and the status code int responsecode = Connection.getresponsecode (); if (Responsecode = = HTTPURLCONNECTION.HTTP_OK) {return Changeinputestream (Connection.getinputstream (), ENC ODE); }} catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.print StackTrace (); } catch (IoexceptiOn e) {//TODO auto-generated catch block E.printstacktrace (); } return ""; /** * Convert an input stream to a string * @param inputstream * @param encode * @return */private static string Changeinputestream (InputStream inputstream,string encode) {//is often called a memory stream, written in memory Bytearrayoutputstream OUTPU TStream = new Bytearrayoutputstream (); byte[] data = new byte[1024]; int len = 0; String result = ""; if (InputStream! = null) {try {while (len = inputstream.read (data))!=-1) { Data.tostring (); Outputstream.write (data, 0, Len); }//result is the result = new String (Outputstream.tobytearray (), encode) in the Dopost function set on the server side; Outputstream.flush (); } catch (IOException e) {//TODO auto-generated catch blOck E.printstacktrace (); }} return result; } public static void Main (string[] arsg) {map<string, string> params = new hashmap<string, String > (); Params.put ("username", "Lili"); Params.put ("password", "123"); String result = Sendpostmessage (params, "utf-8"); System.out.println ("result->" +result); } }
Below is the servlet code on the server side:
Package Com.login.manager; Import Java.io.ByteArrayOutputStream; Import java.io.IOException; Import Java.io.InputStream; Import Java.io.InputStreamReader; Import Java.io.PrintWriter; Import javax.servlet.ServletException; Import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; public class Loginaction extends HttpServlet {/** * Constructor of the object. */Public Loginaction () {super (); }/** * Destruction of the servlet. <br> * * public void Destroy () {Super.destroy ();//Just puts "destroy" string in Log// Put your code here} public void doget (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {this.dopost (request, response); }/** * The DoPost method of the servlet. <br> * * This method is Called when the a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the Serv ER to the client * @throws servletexception If a error occurred * @throws IOException if an error occurred */public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception , IOException {response.setcontenttype ("text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); PrintWriter out = Response.getwriter (); String username = request.getparameter ("username"); The content is: Password=123&username=lili System.out.println ("username:" +username); String pswd = request.getparameter ("password"); System.out.println ("Password:" +pswd); if (Username.equals ("Zhang San") &&pswd.equals ("123")) {//= server-side returnThe result of Out.print ("LOGIN is success!!!!"); }else{out.print ("Login is FAIL!!!"); } out.flush (); Out.close (); }/** * Initialization of the servlet. <br> * * @throws servletexception If an error occurs */public void init () throws Servletexcepti on {//Put your code here}}
Server-side code using servlet-built ...
This is the result of the operation:
Service-side:
The content received on the server is: Password=123&username=lili was parsed by it.
Send HTTP requests in Android in post mode