The Android Network program transmits data to the server (ii)

Source: Internet
Author: User

The Android Network program transmits data to the server (ii)


Please respect the results of other people's work, reproduced please specify the Source: Android Network Programming transfer data to the server (ii)

I have in the "Android network programming data to the server (a)" article describes how to pass the data to the server by get method, pass the data by get method is mainly applicable to the size of the data not more than 2KB, and security requirements are not high. The following describes the delivery of data from the primary to the server via post.


First, pass the data to the server through the post way

Passing data to the server via post is a major way for Android applications to develop and submit data to the server for applications where data is large, data types are complex, and data security is high.

1. Create Server-side:

Server-side project structure:


First step: Create a controller servlet
Package Com.jph.sp.servlet;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.HttpServletResponse; @WebServlet ("/ Servletforpostmethod ") public class Servletforpostmethod extends HttpServlet {private static final long Serialversionuid = 1L;          protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// TODO auto-generated method stub}protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {String name= request.getparameter ("name"); String pwd= request.getparameter ("pwd"); System.out.println ("Name from POST method:" + name); System.out.println ("pwd from POST method:" + pwd);}}


The server-side project has been completed. Start creating an Android -side project below.


2. Create the Android side:

Android End Project Structure:



Step One: Create a business logic layer for Android-side projects

Core code: Senddatetoserver.java:

Package Com.jph.sp.service;import Java.io.outputstream;import Java.net.httpurlconnection;import Java.net.URL; Import Java.net.urlencoder;import java.util.hashmap;import java.util.map;import android.os.handler;/** * Send data to server via post * @author JPH * date:2014.09.27 */public class Senddatetoserver {private static String url= "http://10.219 .61.117:8080/serverforpostmethod/servletforpostmethod ";p ublic static final int send_success=0x123;public static Final int send_fail=0x124;private Handler handler;public senddatetoserver (Handler Handler) {//TODO auto-generated constructor Stubthis.handler=handler;} /** * Send data to server via post * @param name username * @param pwd password */public void senddatatoserver (String name,string pwd) {//TODO Auto-generated method Stubfinal map<string, String>map=new hashmap<string, string> (); Map.put ("Name", name ); Map.put ("pwd", pwd); new Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method Stubtry {if (s Endpostrequest (Map,url, "Utf-8")) {handLer.sendemptymessage (send_success);//notify the main thread that the data was sent successfully}else {//Send data to server failed}} catch (Exception e) {//TODO auto-generated Catch Blocke.printstacktrace ();}}}). Start ();} /** * Send POST request * @param map request parameter * @param URL request path * @return * @throws Exception */private boolean sendpostrequest (MAP&L T String, string> param, String url,string encoding) throws Exception {//TODO auto-generated method stub//http://10.219. 61.117:8080/serverforpostmethod/servletforpostmethod?name=aa&pwd=124stringbuffer sb=new StringBuffer (URL); (!url.equals ("") &!param.isempty ()) {Sb.append ("?"); For (map.entry<string, String>entry:param.entryset ()) {Sb.append (Entry.getkey () + "="), Sb.append ( Urlencoder.encode (Entry.getvalue (), encoding)); Sb.append ("&");} Sb.deletecharat (Sb.length ()-1);//Delete the last character of the string "&"}byte[]data=sb.tostring (). GetBytes (); HttpURLConnection conn= (httpurlconnection) new URL (URL). OpenConnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("POST");//Set Request mode is Postconn.setdooutput (true);/allow external transmission of data conn.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");//Set form data encoding to name/ Value pairs Conn.setrequestproperty ("Content-length", data.length+ ""); OutputStream outputstream=conn.getoutputstream ();// Open the input stream Outputstream.write (data) of the server,//write to the server's output stream Outputstream.flush (); if (Conn.getresponsecode () ==200) {return true;} return false;}}


Step Three: Create activity

Package Com.jph.sp.activity;import Com.jph.sp.service.senddatetoserver;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.app.activity;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import android.widget.toast;/** * Passing data to the server via post is a major way for Android application development * To submit data to the server, for applications where data is large, data types are complex, and data security is high. * @author JPH * date:2014.09.27 */public class Mainactivity extends Activity {private EditText edtname,edtpwd;private butt On Btnsend; Handler handler=new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {case Senddatetoserver.send_ SUCCESS:Toast.makeText (Mainactivity.this, "landing success", Toast.length_short). Show (); Break;case Senddatetoserver.send_ FAIL:Toast.makeText (mainactivity.this, "Login Failed", Toast.length_short). Show (); break;default:break;}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activitY_main), Edtname= (EditText) Findviewbyid (r.id.edtname), edtpwd= (EditText) Findviewbyid (R.ID.EDTPWD); Btnsend= ( Button) Findviewbyid (r.id.btnsend), Btnsend.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick ( View v) {//TODO auto-generated method stubstring Name=edtname.gettext (). toString (); String Pwd=edtpwd.gettext (). toString (); if (Edtname.equals ("") | | Edtpwd.equals ("")) {Toast.maketext ("") {mainactivity.this, "user name or password cannot be empty", Toast.length_long). Show (); else {new Senddatetoserver (handler). Senddatatoserver (name, PWD);}});}}

The Android project is now complete. Let's look at how the app works:

Android Run:




The Android Network program transmits data to the server (ii)

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.