The second method of data interaction between the Android client and the server is android server.

Source: Internet
Author: User

The second method of data interaction between the Android client and the server is android server.

There are many examples on the Internet to demonstrate how the Android client interacts with the server. However, these examples are mostly complicated, which is not good for beginners, here are some examples of simple code and clear logic interaction. This blog introduces the second one:

I. server side:

Code 1: Add 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 = 6792316567928634227l; public void doPost (HttpSer VletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/plain; charsets = UTF-8"); request. setCharacterEncoding ("UTF-8"); System. err. println (request. getParameter ("clientData"); PrintWriter printWriter = response. getWriter (); printWriter. print ("Hello Android client! "); PrintWriter. flush (); printWriter. close ();}}

Code 2: modify 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>

Ii. Android mobile client:

Code 1: Add 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. htt P. 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. handler; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. B Utton; 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 () {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! "); Try {Message message = new Message (); Bundle bundle = new Bundle (); httpRequest. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // sets the request parameter item HttpClient httpClient = new DefaultHttpClient (); HttpResponse httpResponse = httpClient.exe cute (httpRequest); // executes the request to return a response if (httpResponse. getStatusLine (). getStatusCode () = 200) {// determine whether the bundle request is successful. putString ("msg", EntityUtils. toString (httpResponse. getE Ntity ();} else {bundle. putString ("msg", "no response from the Android server is obtained! ");} Message. setData (bundle); handler. sendMessage (message);} catch (ClientProtocolException e) {e. printStackTrace ();} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}). start () ;}}) ;}private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message message) {super. handleMessage (message); Bundle bundle = message. getData (); String msg = bundle. getString ("msg"); Toast. makeText (getApplicationContext (), msg, Toast. LENGTH_LONG ). show ();}};}

Code 2: Add 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>

Download the Demo]

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.