Android Post sends HTTP requests, androidpost

Source: Internet
Author: User

Android Post sends HTTP requests, androidpost

The Post method is more complex than the Get method, because the request parameters must be placed in the body of the http request, so the Request body must be constructed.

Steps:

1. Construct a URL

URL url = new URL (PATH); 2. Set the connection
HttpURLConnection connection = (HttpURLConnection) url. openConnection (); connection. setConnectTimeout (3000); connection. setDoInput (true); // indicates retrieving data from the server connection. setDoOutput (true); // indicates writing data to the server // The size and length of the byte for obtaining the upload information connection. setRequestMethod ("POST"); // whether to use the cache connection. setUseCaches (false); // indicates that the request body type is text-type connection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); connection. setRequestProperty ("Content-Length", String. valueOf (mydata. length); connection. connect ();

3. Write the Request body

Map <String, String> params = new HashMap <String, String> (); params. put ("username", "lili"); params. put ("password", "123"); StringBuffer buffer = new StringBuffer (); try {// write the Request 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 &, with one more. The buffer has been set for the subject. deleteCharAt (buffer. length ()-1); byte [] mydata = buffer. toString (). getBytes (); // get the output stream and output data OutputStream outputStream = connection to the server. getOutputStream (); outputStream. write (mydata, 0, mydata. length );

4. Read the returned data and close the connection.

// It is usually called a memory stream. It is written in 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 (); outputStream. write (data, 0, len);} // result is the result = new String (outputStream. toByteArray (), encode); outputStream. flush ();

The code below: 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 {url = new URL (PATH);} catch (MalformedURLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/ *** @ param params the url parameter * @ param encode Byte encoding * @ return */public static String sendPostMessage (Map <String, String> params, String encode) {StringBuffer buffer = new StringBuffer (); try {// write the request subject 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 &, with one more. The buffer has been set for the subject. deleteCharAt (buffer. length ()-1); byte [] mydata = buffer. toString (). getBytes (); HttpURLConnection connection = (HttpURLConnection) url. OpenConnection (); connection. setConnectTimeout (3000); connection. setDoInput (true); // indicates retrieving data from the server connection. setDoOutput (true); // indicates writing data to the server // The size and length of the byte for obtaining the upload information connection. setRequestMethod ("POST"); // whether to use the cache connection. setUseCaches (false); // indicates that the request body type is text-type connection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); connection. setRequestProperty ("Content-Length", String. valueOf (my Data. length); connection. connect (); // connection. You can do this without writing ..?? To learn more, // obtain the output stream and output data OutputStream outputStream = connection to the server. getOutputStream (); outputStream. write (mydata, 0, mydata. length); // get the server response result and status code int responseCode = connection. getResponseCode (); if (responseCode = HttpURLConnection. HTTP_ OK) {return changeInputeStream (connection. getInputStream (), encode) ;}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch block e. printStackTrace ();} 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) {// usually called memory stream, written in the memory ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); byte [] data = new byte [1024]; int len = 0; string result = ""; if (Indium UtStream! = Null) {try {while (len = inputStream. read (data ))! =-1) {data. toString (); outputStream. write (data, 0, len);} // result is the result = new String (outputStream. toByteArray (), encode); 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 of the server:

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 servle T. <br> ** This method is called when 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 server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doPost (HttpServletRequest request, httpServletResponse response) throws Servlet Exception, 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 uploaded content is: password = 123 & username = lili System. out. println ("username:" + username); String pswd = request. getParameter ("password"); System. out. println ("passw Ord: "+ pswd); if (username. equals ("Zhang San") & pswd. equals ("123") {// indicates that the result returned by the server is 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 ServletException {// Put your code here }}

The server code is built using servlet...

Here is the running result:

Server:

The content received on the server is password = 123 & username = lili ..

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.