Android learning-Http data submission using Post

Source: Internet
Author: User

We know that the data submitted through the Get method is submitted as part of the Url address, and the length of the number of bytes is limited, similar to the Get method, the http-post parameter is URL encoded. However, its variable name and variable value are not transmitted as part of the URL, but are transmitted within the actual HTTP request message. You can use the following code to set the parameters for POST submission: [html] HttpURLConnection urlConnection = (HttpURLConnection) url. openConnection (); urlConnection. setConnectTimeout (3000); urlConnection. setRequestMethod ("POST"); // submit urlConnection in post request mode. setDoInput (true); // reads the data urlConnection. setDoOutput (true); // write data to the server // obtain the size and length of the uploaded information byte [] myData = stringBuilder. toString (). getBytes (); // set the type of the Request body to text, indicating that the currently submitted text data is urlConnection. setRequestP Roperty ("Content-Type", "application/x-www-form-urlencoded"); urlConnection. setRequestProperty ("Content-Length", String. valueOf (myData. length); here we use a case to see how to use the post method to submit data to the server: First we create a java project, as long as we create a class, we create an HttpUtils. java class, [Code as follows]: [html] package com. wujay. utils; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import ja Va. 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: // bdfngdg: 8080/myhttp/servlet/LoginAction"; // server address private static URL url; public HttpUtils () {super () ;}// static code block instantiation url static {Try {url = new URL (PATH);} catch (MalformedURLException e) {e. printStackTrace () ;}/ *** send the message body to the server ** @ param params * @ param encode * @ return */public static String sendPostMessage (Map <String, string> params, String encode) {StringBuilder stringBuilder = new StringBuilder (); if (params! = Null &&! Params. isEmpty () {for (Map. entry <String, String> entry: params. entrySet () {try {stringBuilder. append (entry. getKey ()). append ("= "). append (URLEncoder. encode (entry. getValue (), encode )). append ("&");} catch (UnsupportedEncodingException e) {e. printStackTrace () ;}} stringBuilder. deleteCharAt (stringBuilder. length ()-1); try {HttpURLConnection urlConnection = (HttpURLConnection) url. openConn Ection (); urlConnection. setConnectTimeout (3000); urlConnection. setRequestMethod ("POST"); // submit urlConnection in post request mode. setDoInput (true); // reads the data urlConnection. setDoOutput (true); // write data to the server // obtain the size and length of the uploaded information byte [] myData = stringBuilder. toString (). getBytes (); // set the type of the Request body to text, indicating that the currently submitted text data is urlConnection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); urlConnection. setRequestPr Operty ("Content-Length", String. valueOf (myData. length); // get the output stream and output the content OutputStream outputStream = urlConnection to the server. getOutputStream (); // write data to outputStream. write (myData, 0, myData. length); outputStream. close (); // get the server response result and status code int responseCode = urlConnection. getResponseCode (); if (responseCode = 200) {// return changeInputStream (urlConnection. getInputStream (), encode) ;}} catch (IOEx Ception e) {e. printStackTrace () ;}} return "";} /*** convert an input stream to a specified encoded String ** @ param inputStream * @ param encode * @ return */private static String changeInputStream (InputStream inputStream, String encode) {// memory stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream (); byte [] data = new byte [1024]; int len = 0; String result = null; if (inputStream! = Null) {try {while (len = inputStream. read (data ))! =-1) {byteArrayOutputStream. write (data, 0, len);} result = new String (byteArrayOutputStream. toByteArray (), encode);} catch (IOException e) {e. printStackTrace () ;}} return result;}/*** @ param args */public static void main (String [] args) {Map <String, string> map = new HashMap <String, String> (); map. put ("username", "admin"); map. put ("password", "123456"); String result = sendPostMessage (ma P, "UTF-8"); System. out. println (">>>" + result) ;}} let's create another server project, a web project. Here we create a myhttp project and create a servlet for it first, used to receive parameter access. The servlet configuration is as follows: [html] <servlet> <description> This is the description of my J2EE component </description> <display-name> This is the display name of my J2EE component </display-name> <servlet-name> LoginAction </servlet-name> <servlet-class> com. login. manager. loginAction </servlet-class> </servlet> <servlet-mapping> <servlet-name> LoginAction </servlet-name> <url-pattern>/servlet/LoginAction </url -pattern> </ Servlet-mapping> created LoginAction. the java class inherits HttpServlet: [html] package com. login. manager; import java. io. IOException; 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. */publi C LoginAction () {super ();}/*** Destruction of the servlet. <br> */public void destroy () {super. destroy (); // Just puts "destroy" string in log // Put your code here}/*** The doGet method of the servlet. <br> ** This method is called when a form has its tag value method equals to get. ** @ param request the request send by the client to the server * @ param response the response send by th E server to the client * @ throws ServletException if an error occurred * @ throws IOException if an error occurred */public void doGet (HttpServletRequest request, response) throws ServletException, IOException {this. doPost (request, response);}/*** The doPost method of the servlet. <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 ServletException, IOException {response. setContentType ("text/html; charset = UTF-8"); request. setCharacter Encoding ("UTF-8"); response. setCharacterEncoding ("UTF-8"); PrintWriter out = response. getWriter (); String userName = request. getParameter ("username"); String passWord = request. getParameter ("password"); System. out. println ("userName:" + userName); System. out. println ("passWord:" + passWord); if (userName. equals ("admin") & passWord. equals ("123456") {out. print ("login successful! ");} Else {www.2cto.com out. print ("login failed");} out. flush (); out. close ();}/*** Initialization of the servlet. <br> ** @ throws ServletException if an error occurs */public void init () throws ServletException {// Put your code here }}

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.