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

Source: Internet
Author: User

Android Network Programming transfer data to the server (i)

Please respect other people's labor results, reproduced please specify the source: The Android Network program transmits data to the server (a)


because Android the program needs to communicate with the server, so it needs the support provided by the server side.

First,throughGETway to pass data to the server

through GET The method of uploading data is mainly applicable to data size not exceeding 2KB , and the security requirements are not high.

1.To create a server-side:

Server-side project structure:



First step: Create a controllerServlet 
Package Com.jph.sgm.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;/** * servlet implementation Class Servletforgetmethod */@WebServlet ("/servletforgetmethod") public class Servletforgetmethod extends HttpServlet {           Private static final long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public Servletforgetmethod () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse R esponse) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated method stub//Gets the requested parameter (decoded using Utf-8, then ISO8859-1-encoded)//string name=new String ( Request.getparameter ("name"). GetBytes ("Iso8859-1"), "Utf-8"); String Name=requeSt.getparameter ("name"); String pwd=request.getparameter ("pwd"); System.out.println ("Name:" +name+ "pwd:" +pwd);} /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method stub}}

Step two: TestServlet

Publish the project and enter it in the browser: http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124

You can see the output as shown in the console:



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

2.CreateAndroidEnd:

Android End Project Structure:



First step: CreateAndroidbusiness Logic layer of the end project

Core code: Senddatetoserver.java:

Package Com.jph.sdg.service;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 get mode * @author JPH * Date : 2014.09.27 */public class Senddatetoserver {private static String url= "http://10.219.61.117:8080/ServerForGETMethod/ Servletforgetmethod ";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 by Get mode * @param name username * @param pwd password */public void senddatatoserver (String name,string pwd) {//TODO A Uto-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 (SE Ndgetrequest (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 GET request * @param map request parameter * @param URL request path * @return * @throws Exception */private boolean sendgetrequest (map< String, string> param, String url,string encoding) throws Exception {//TODO auto-generated method Stub//http://localho St:8080/serverforgetmethod/servletforgetmethod?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 "&"}httpurlconnection conn= (httpurlconnection) New URL ( Sb.tostring ()). OpenConnection (); Conn.setconnecttimeout (getif); Conn.setrequestmethod ("GET");//Set request by Conn.getresponsecode () ==200) {return true;} return false;}}

Step three: CreateActivity

Package Com.jph.sdg.activity;import Com.jph.sdg.r;import Com.jph.sdg.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;/** * Send data to the server by Get method, upload data by Get method is mainly applicable to the number of * according to the size of not more than 2KB, And the security requirements are not 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);}});}}

so far Android the end project has been completed. Let's look at how the APP works:

Android Run:


2


Second,on the adoptionGETway to pass data to the server, the Chinese garbled solution

When the client sends Chinese to the server, the server side will appear garbled, such as:




The main reason for garbled characters is that Android the client we are using is UTF-8 encoding, and Tomcat The default is to use Iso8858-1 code, so there will be garbled Chinese phenomenon.

There are two types of solutions:

The first of these solutions:

is to use UTF-8 decode the request parameter to get the kanji and then pass iso8859-1 to encode. At this point the server-side Servlet is:

Package Com.jph.sgm.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;/** * servlet implementation Class Servletforgetmethod */@WebServlet ("/servletforgetmethod") public class Servletforgetmethod extends HttpServlet {           Private static final long serialversionuid = 1L;        /** * @see httpservlet#httpservlet () */public Servletforgetmethod () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse R esponse) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated method stub//Gets the requested parameter (decoded with Utf-8 and then iso8859-1 encoded) string Name=new string ( Request.getparameter ("name"). GetBytes ("Iso8859-1"), "Utf-8");//string Name=requeSt.getparameter ("name"); String pwd=request.getparameter ("pwd"); System.out.println ("Name:" +name+ "pwd:" +pwd);} /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method stub}}

 

Running results such as:




Second Solution:

Below we adopt the way of filter to solve garbled problem:

First step: Create a Filter filter.

Encodingfilter.java

Package Com.jph.sgm.filter;import Java.io.ioexception;import Javax.servlet.filter;import javax.servlet.FilterChain ; import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import javax.servlet.ServletRequest; Import Javax.servlet.servletresponse;import Javax.servlet.annotation.webfilter;import javax.servlet.http.httpservletrequest;/** * servlet Filter Implementation class Encodingfilter */@WebFilter ("/*")      public class Encodingfilter implements Filter {/** * Default constructor. */Public Encodingfilter () {//TODO auto-generated constructor stub}/** * @see Filter#destroy () */public VO  ID Destroy () {//TODO auto-generated method stub}/** * @see filter#dofilter (servletrequest, Servletresponse, Filterchain) */public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, Servlete xception {//TODO auto-generated method Stubhttpservletrequest req= (httpservletrequest) request;if ("GET". Equals ( Req.getmethod ()) {Httpservletrequestencodingwrapper wrapper=new httpservletrequestencodingwrapper (req); Chain.doFilter (Wrapper, Response);} else {req.setcharacterencoding ("Utf-8"); Chain.dofilter (request, Response);}} /** * @see filter#init (filterconfig) */public void init (Filterconfig fconfig) throws Servletexception {//TODO Auto-genera Ted Method stub}}

The filter above is set to the filter path as */ so it filters all the Servlet .

a wrapper was used in the filter above, Httpservletrequestencodingwrapper.java

Package Com.jph.sgm.filter;import Java.io.unsupportedencodingexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletrequestwrapper;public Class Httpservletrequestencodingwrapper extendshttpservletrequestwrapper {Private HttpServletRequest Request;public Httpservletrequestencodingwrapper (HttpServletRequest request) {//TODO auto-generated constructor Stubsuper (request) ; this.request=request;} @Overridepublic string GetParameter (string name) {//TODO auto-generated method stubstring Value=request.getparameter ( Name), if (value!=null) {try {//decode with utf-8, and then encode with iso8859-1 return new String (Value.getbytes ("iso8859-1"), "Utf-8");} catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} return Super.getparameter (name);}}


rerun the project to see that the server will use the data sent by the client UTF-8 to decode, use the iso8859-1 to encode. Run as follows:



The Android Network program transmits data to the server (ii)--passing data to the server via post

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

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.