Android-Sends data (GET) to the server.

Source: Internet
Author: User

Here, using the HTTP protocol, the request is sent to the server through a GET request, which is suitable for small amounts of data and low data security requirements.

One, server side, using servlet.

On the server side, define a subclass of HttpServlet, and a subclass of filter (for uniform encoding to prevent garbled characters).

Package Spt.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;/** * type ' http://localhost : 8080/receiveandroid/servletforgetmethod?name=juk&pwd=lis ' * for the browser. */@WebServlet ("/servletforgetmethod") public class Servletforgetmethod extends HttpServlet {private static final long Serialversionuid = 1l;/** * @see httpservlet#httpservlet () */public Servletforgetmethod () {super ();} /** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse * response) */protected void Doget (HttpS Ervletrequest request, HttpServletResponse response) throws Servletexception, IOException {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 Ser Vletexception, IOException {//TODO auto-generated method stub}}

 

Package Spt.servlet.filter;import Java.io.ioexception;import Java.io.unsupportedencodingexception;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;import  Javax.servlet.http.httpservletrequestwrapper;//filter all servlets. @WebFilter ("/*") public class Encodingfilter Implements Filter {public void DoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain Filterchain) throws IOException, servletexception {httpservletrequest httpreq = (httpservletrequest) servletRequest;if ("GET". Equals (Httpreq.getmethod ())) Filterchain.dofilter (new Httpservletrequestencodingwrapper (Httpreq), Servletresponse), else {httpreq.setcharacterencoding ("Utf-8"); Filterchain.dofilter (Httpreq, Servletresponse);}} public void init (Filterconfig filterconfig) throws Servletexception {//TODO auto-generated method Stub}/**inner class dealing for ' GET ' method. * @author Administrator *2015-1-27 */private class Httpservletrequestencodingwrapper extends Httpservletrequestwrapper {Public Httpservletrequestencodingwrapper (HttpServletRequest request) {super (request);} @Overridepublic string GetParameter (string name) {//encode with ' ISO ', and than decode with ' UTF '. String val = Super.getrequest (). GetParameter (name), if (null! = val) {try {return new String (Val.getbytes ("iso8859-1"), "U Tf-8 ");} catch (Unsupportedencodingexception e) {e.printstacktrace ();}} return Super.getparameter (name);}} public void Destroy () {//TODO auto-generated method stub}}

On the host (server), enter ' Http://localhost:8080/ReceiveAndroid/ServletForGETMethod?name=juk&pwd=lis ' in the browser, if you want to print the desired results in the console, Indicates that the server-side servlet has been written.

Second, the Android business logic Layer class, mainly is the business logic independent of the activity of Android.

Package Spt.http.get.assist;import Java.io.ioexception;import Java.net.httpurlconnection;import Java.net.malformedurlexception;import Java.net.url;import Java.net.urlencoder;import Java.util.HashMap;import Java.util.map;import Java.util.map.entry;import android.os.handler;/** The class that the user sends data to the server side. * @author Administrator * */public class Senddatatoserver {private static final int time_out = 10000;//timeout.//URL of the connection server . private static final String URL = "Http://192.168.1.101:8080/ReceiveAndroid/ServletForGETMethod";// Identifies whether the connection to the server was successful. public static final int send_success = 1;public static final int send_fail = 0;private Handler Handler = null ;p ublic senddatatoserver (Handler Handler) {this.handler = Handler;} /** * Send data to the server. * * @param name * @param pwd */public void Send (string name, string pwd) {//Here the params is to be passed to another method, plus final in order to prevent modification. Final MAP&L T String, string> params = new hashmap<string, string> ();p arams.put ("name", name);p arams.put ("pwd", pwd);// Start a new thread to connect to the server. New Runnable () {@Overridepublic void Run () {//Use GET request to connect. try {if (Getsend (params, URL, "Utf-8")) Handler.sendemptymessage (send_success); Elsehandler.sendemptymessage (Send_fail);} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}). Start ();} /** the method that sent the GET request. * @param the key-value pair of the params request parameter. * @param URL * @param encoding encodes the parameter values using the specified encoding. * @return * @throws malformedurlexception * @throws ioexception */private boolean getsend (map<string, string> params , String url,string encoding) throws Malformedurlexception, IOException {StringBuilder sb = new StringBuilder ();//Add to URL Parameters. Sb.append (URL). Append ("?"); For (entry<string, string> param:params.entrySet ()) {Sb.append (Param.getkey ()). Append ("="). Append ( Urlencoder.encode (Param.getvalue (), encoding)). Append ("&");} if (params.size () > 0) Sb.deletecharat (sb.length ()-1); Remove the ' & ' at the end. HttpURLConnection conn = (httpurlconnection) New URL (Sb.tostring ()). OpenConnection (); Conn.setconnecttimeout (TIME_ OUT); conn. Setrequestmethod ("GET"); Get is case sensitive. return Conn.getresponsecode () = = 200; equals 200 to send success.}}

  III: Activity class:

Package Spt.http.get.activity;import Java.lang.ref.weakreference;import Spt.http.get.assist.SendDataToServer; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.Toast;public Class Mainactivity extends Activity {//view.private EditText edt_name = null;private EditText edt_pwd = null;private Butto n BTN_OK = null, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); Initlistener ();} /** * Initialize view. */private void Initview () {edt_name = (EditText) Findviewbyid (r.id.edt_name); edt_pwd = (EditText) Findviewbyid (R.id.edt _PWD) Btn_ok = (Button) Findviewbyid (R.ID.BTN_OK);//test:edt_name.settext ("Hello"); Edt_pwd.settext ("abc");} /** uses static internal classes to resolve the ' This Handler class should is static or leaks might occur ' to avoid memory leaks. * @author Administrator * */private Static classStatushandler extends Handler {weakreference<mainactivity> imainactivity = Null;public Statushandler ( Mainactivity mainactivity) {imainactivity = new weakreference<mainactivity> (mainactivity);} @Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case senddatatoserver.send_success:// There are Imainactivity.get () and Imainactivity.getclass (). Toast.maketext (Imainactivity.get (), "Send Success", Toast.length_short). Show (); Break;case Senddatatoserver.send_fail: Toast.maketext (Imainactivity.get (), "Send Failed", Toast.length_short). Show (); Break;default:throw New RuntimeException (" Unknown send result! ");}} /** * Handler that handles the status of whether the send is successful. */private final Handler Handler = new Statushandler (this);/** * Initialize listener. */private void Initlistener () {Btn_ok.setonclicklistener (new Button.onclicklistener () {@Overridepublic void OnClick ( View v) {String name = Edt_name.gettext (). toString (); String pwd = Edt_pwd.gettext (). toString (); if (Name.isempty () | | | Pwd.isempty ()) {Toast.maketext (Mainactivity.this, " User name and password cannot be empty ", toast.length_short). Show (); return;} New Senddatatoserver (handler). Send (name, PWD);}});}}

A little note is that the subclass of Handler in the activity class is defined as a static class and holds a weak reference to the activity to prevent memory leaks. Brief explanation in my blog Android-this Handler class should be static or Leaks might occur. In.

Four, add the necessary permissions

In Androidmanifest.xml, add

<android:name= "Android.permission.INTERNET"/>

Access to the network.

Android-Sends data (GET) to the server.

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.