Android Developers use the POST method to request and send data to the server.

Source: Internet
Author: User

Android Developers use the POST method to request and send data to the server.
The GET method is described above. Now try POST
#1. First, use a new servlet to process login requests

package com.wzw.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class LoginServlet */public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public LoginServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username=request.getParameter("username");String password=request.getParameter("password");if(username.equals("admin")&&password.equals("123456")){response.getWriter().println("success");}else{response.getWriter().println("failed");}}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub
this.doGet(request,response);}}
#2. layout files are also very simple
     
      
          
      
  
 

#3 Implementation in mainactivity
Package com. wzw. submitdata; import com. wzw. submitdata. utils. netUtil; import android. OS. bundle; import android. app. activity; import android. view. menu; import android. view. view; import android. widget. editText; import android. widget. toast; public class MainActivity extends Activity {private EditText etUsername; private EditText etPassword; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); etUsername = (EditText) findViewById (R. id. et_username); etPassword = (EditText) findViewById (R. id. et_password);} public void doGet (View v) {final String username = etUsername. getText (). toString (); final String password = etPassword. getText (). toString (); new Thread (new Runnable () {@ Overridepublic void run () {// the access network needs to be implemented in the Child Thread. Use get to get data final String state = NetUtil. loginOfGet (username, password); // run the runOnUiThread (new Runnable () {public void run () {// operation on the main thread. The result Toast is displayed. makeText (MainActivity. this, state, 0 ). show ();}});}}). start ();} public void doPost (View v) {final String username = etUsername. getText (). toString (); final String password = etPassword. getText (). toString (); new Thread (new Runnable () {@ Overridepublic void run () {final String state = NetUtil. loginOfPost (username, password); // run the runOnUiThread (new Runnable () {public void run () {// operation on the main thread. The result Toast is displayed. makeText (MainActivity. this, state, 0 ). show ();}});}}). start ();}}


#4. Specific methods for handling GET and POST
Package com. wzw. submitdata. utils; import java. io. byteArrayOutputStream; import java. io. inputStream; import java. io. outputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; public class NetUtil {/*** use GET to access the network * @ param username * @ param password * @ return result returned by the server */public static String loginOfGet (String username, string password) {HttpURLConnection con N = null; try {String data = "username =" + username + "& password =" + password; URL url = new URL ("http: // 192.168.1.4: 8080/AndroidServer/LoginServlet? "+ Data); conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (10000); conn. setreadtimeouts (5000); conn. connect (); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); String state = getStringFromInputStream (is); return state ;}} catch (Exception e) {e. printStackTrace ();} finally {if (conn! = Null) {conn. disconnect () ;}} return null ;} /*** use POST to access the network * @ param username * @ param password * @ return */public static String LoginOfPost (String username, String password) {HttpURLConnection conn = null; try {URL url = new URL ("http: // 192.168.1.4: 8080/AndroidServer/LoginServlet"); conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("POST"); conn. setConnectTimeout (10000); conn. setReadTimeou T (1, 5000); conn. setDoOutput (true); // The String data = "username =" + username + "& password =" + password; OutputStream out = conn. getOutputStream (); out. write (data. getBytes (); out. flush (); out. close (); conn. connect (); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); String state = getStringFromInputStream (is); return state ;}} catch (Exception e) {e. printStackTrace ();} finally {if (con N! = Null) {conn. disconnect () ;}} return null;}/*** returns a String * @ param is * @ return * @ throws Exception */private static String getStringFromInputStream (InputStream is) based on the input stream) throws Exception {ByteArrayOutputStream baos = new ByteArrayOutputStream (); byte [] buff = new byte [1024]; int len =-1; while (len = is. read (buff ))! =-1) {baos. write (buff, 0, len);} is. close (); String html = baos. toString (); baos. close (); return html ;}}




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.