Android Network Programming-data transfer to servers (1)

Source: Internet
Author: User

Android Network Programming-data transfer to servers (1)

Android Network Programming-data transfer to servers (1)

Please respect others' labor achievements and repost the Source: transfer data from Android Network programming to the server (I)


Because the Android program needs to communicate with the server, it needs the support provided by the server.

1. pass data to the server through GET

The GET method is applicable when the data size does not exceed 2 kb and the security requirements are not high.

1. Create a server:

Server project structure:



Step 1: Create a controller Servlet
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, response) */protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {// TODO Auto-generated method stub // get the request parameter (decoded using UTF-8 and then encoded in ISO8859-1) // 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 2: Test Servlet

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

You can see the output in the console:



So far, the server project has been completed. Create an Android project.

2. Create an Android client:

Android project structure:



Step 1: Create the business logic layer of the Android 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 the server through GET * @ author jph * Date: 2014.09.27 */public class SendDateToServer {private static String url = "http: // 10.219.61.117: 8080/ServerForGETMethod/ServletForGETMethod "; public 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 the server through Get * @ param name username * @ param pwd password */public void SendDataToServer (String name, String pwd) {// TODO Auto-generated method stubfinal Map
 
  
Map = new HashMap
  
   
(); Map. put ("name", name); map. put ("pwd", pwd); new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {if (sendGetRequest (map, url, "UTF-8") {handler. sendEmptyMessage (SEND_SUCCESS); // notifies the master thread that data has been successfully sent} else {// failed to send data to the server} 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
   
    
Param, String url, String encoding) throws Exception {// TODO Auto-generated method stub // http: // localhost: 8080/ServerForGETMethod/ServletForGETMethod? Name = aa & pwd = 124 StringBuffer sb = new StringBuffer (url); if (! Url. equals ("")&! Param. isEmpty () {sb. append ("? "); For (Map. Entry
    
     
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 "&"} HttpURLConnection conn = (HttpURLConnection) new URL (sb. toString ()). openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); // set the request method to GETif (conn. getResponseCode () = 200) {return true;} return false ;}}
    
   
  
 

Step 3: Create an Activity

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;/*** use the GET method to send data to the server. Using the GET method to upload data is mainly applicable to the data size not exceeding 2 kb, and does not have high security requirements. * @ Author jph * Date: 2014.09.27 */public class MainActivity extends Activity {private EditText edtName, edtPwd; private Button btnSend; Handler handler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {case SendDateToServer. SEND_SUCCESS: Toast. makeText (MainActivity. this, "Login successful", 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, "the user name or password cannot be blank", Toast. LENGTH_LONG ). show ();} else {new SendDateToServer (handler ). sendDataToServer (name, pwd );}}});}}

So far, the Android project has been completed. Let's take a look at the APP running effect:

Android running:


2


2. Solutions for garbled Chinese characters when data is transmitted to the server through GET

When the client sends Chinese characters to the server, garbled characters may occur on the server, such:


Vcq9tKu13cr9vt24 + Lf + zvHG98qxo6zW0M7EwtLC67XEveK + 9re9sLg = ">


The main reason for garbled characters is that Android client we use UTF-8 encoding, while Tomcat uses ISO8858-1 encoding by default, so there will be Chinese garbled characters.

There are two solutions:

Solution 1:

Is to use the UTF-8 decoding request parameters to get Chinese characters, and then through the ISO8859-1 for encoding. In this case, the server 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, response) */protected void doGet (HttpServletRequest request, response) throws ServletException, IOException {// TODO Auto-generated method stub // get the request parameter (decoded using UTF-8 and then encoded in ISO8859-1) 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 }}

The running result is as follows:




Solution 2:

Below we use the filter method to solve the garbled problem:

Step 1: Create a 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 void destroy() {// TODO Auto-generated method stub}/** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// 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-generated method stub}}

The above filter filters all servlets because the filter path is.

The above filter uses a wrapper, HttpServletRequestEncodingWrapper. java

Package com. jph. sgm. filter; import java. io. unsupportedEncodingException; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletRequestWrapper; public class implements writable {private HttpServletRequest request; public HttpServletRequestEncodingWrapper (HttpServletRequest request) {// TODO Auto-generated constructor stubsuper (re Quest); this. request = request ;}@ Overridepublic String getParameter (String name) {// TODO Auto-generated method stubString value = request. getParameter (name); if (value! = Null) {try {// decodes with UTF-8, and then uses the ISO8859-1 to encode return new String (value. getBytes ("ISO8859-1"), "UTF-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} return super. getParameter (name );}}


Re-run the project to see that the server decodes the data sent from the client with the UTF-8 and encodes it with the ISO8859-1. Run the following command:



Android Network Programming transmits data to the server (2) -- transmits data to the server through POST

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.