The third way to interact with Android client and server-side data

Source: Internet
Author: User

There are many examples on the web to demonstrate how Android client and server-side data interact but most of these examples are cumbersome, for beginners This is unfavorable, and now introduce several simple, logical and clear interactive examples, this blog introduces the Third Kind:

First, server-side:

Code Listing 1: Adding a file named "Androidserverservlet.java"

Package Com.ghj.packageofservlet;import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public Class Androidserverservlet extends HttpServlet {private static final long serialversionuid = 6792396567928634227l;public void D Opost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/plain; Charset=utf-8 "); Request.setcharacterencoding (" UTF-8 "); System.err.println (Request.getparameter ("Clientdata")); PrintWriter printwriter = Response.getwriter ();p rintwriter.print ("Hello Android client! ");p Rintwriter.flush ();p rintwriter.close ();}}

Code Listing 2: Modifying a file named "Web. Xml"

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "Http://java.sun.com/xml/ns/javaee" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http ://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><servlet><servlet-name>androidserverservlet</ servlet-name><servlet-class>com.ghj.packageofservlet.androidserverservlet</servlet-class></ Servlet><servlet-mapping><servlet-name>androidserverservlet</servlet-name><url-pattern >/AndroidServerServlet</url-pattern></servlet-mapping></web-app>

Second, Android mobile phone client:

Code Listing 1: Adding a file named "Androidclientactivity.java"

Package Com.example.androidclient;import Java.io.ioexception;import Java.io.unsupportedencodingexception;import Java.util.arraylist;import Java.util.list;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.protocol.http;import Org.apache.http.util.entityutils;import Android.app.activity;import Android.os.bundle;import Android.os.Looper; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public class Androidclientactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.android_client); Button Sendbutton = (Button) Findviewbyid (R.id.send_button); Sendbutton.setonclicklistener (new Onclicklistener () {@    overridepublic void OnClick (View v) {New Thread (new Runnable () {@Override public void run () {looper.prepare ();    HttpPost HttpRequest = new HttpPost ("Http://172.16.99.207:8080/AndroidServer/AndroidServerServlet");    list<namevaluepair> params = new arraylist<namevaluepair> (); Params.add (New Basicnamevaluepair ("Clientdata", "Hello Server side!")    ")); try {httprequest.setentity (new urlencodedformentity (params, HTTP.                Utf_8));//Set request parameter entry HttpClient HttpClient = new Defaulthttpclient (); HttpResponse HttpResponse = Httpclient.execute (HttpRequest);//Execute Request return response if (Httpresponse.getstatusline (). GetS Tatuscode () = = 200) {//Determine if the request was successful Toast.maketext (Androidclientactivity.this, entityutils.tostring (HttpResponse                . GetEntity ()), Toast.length_long). Show (); }else{Toast.maketext (AndroidclientactivIty.this, "did not get the response to the Android server side!                ", Toast.length_long). Show ();    }} catch (Clientprotocolexception e) {e.printstacktrace ();    } catch (Unsupportedencodingexception e) {e.printstacktrace ();    } catch (IOException e) {e.printstacktrace ();    } looper.loop (); }}). Start ();}});}}

Note : Lines 41st and 61st above are not necessary, otherwise java.lang.RuntimeException:Can ' t create handler inside thread that have not called Looper.prepare () exception, see another article named "can in Android" create handler inside thread that have not called looper.prepare () exception "blog.

Code Listing 2: Adding a file named "Android_client.xml"

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">   <button       android:id=" @+id/send_button "       android:layout_width=" Wrap_content "       android:layout_height= "wrap_content"       android:layout_centerhorizontal= "true"       android:layout_ Centervertical= "true"       android:text= "@string/hello_server"/></relativelayout>

"0 minutes to download the demo"

Third method of interaction between Android client and server-side data

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.