Androidclient和server第一種方法端資料交換

來源:互聯網
上載者:User

標籤:

        網上有一個非常不同的情況來證明Android用戶端和server如何結束的資料,但這些實施例大多相互作用更複雜,對於那些誰剛開始學習它是有害的,現在介紹一些簡單的代碼、邏輯清晰的互動樣本,首先介紹本部落格:

        一、server端:

        代碼1:加入名為“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 doPost(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();printWriter.print("您好Android用戶端!");printWriter.flush();printWriter.close();}}

        代碼2:改動名為“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>

        二、Android手機用戶端:

        代碼1:加入名為“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.StrictMode;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);if (android.os.Build.VERSION.SDK_INT > 9) {    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();    StrictMode.setThreadPolicy(policy);}Button sendButton = (Button) findViewById(R.id.send_button);sendButton.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {HttpPost httpRequest = new HttpPost("http://172.16.99.207:8080/AndroidServer/AndroidServerServlet");    List<NameValuePair> params = new ArrayList<NameValuePair>();    params.add(new BasicNameValuePair("clientData", "您好server端!

")); try { httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//佈建要求參數項 HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest);//運行請求返迴響應 if(httpResponse.getStatusLine().getStatusCode() == 200){//推斷是否請求成功 Toast.makeText(AndroidClientActivity.this, EntityUtils.toString(httpResponse.getEntity()), Toast.LENGTH_LONG).show(); }else{ Toast.makeText(AndroidClientActivity.this, "沒有擷取到Androidserver端的響應。", Toast.LENGTH_LONG).show(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}});}}

        注意:請注意“AndroidClientActivity.java”檔案裡34、35、36和37這4行代碼——假設沒有這幾行代碼,則會出現android.os.NetworkOnMainThreadException異常,關於該異常請參見還有一篇名為《 android.os.NetworkOnMainThreadException異常》部落格

        代碼2:加入名為“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點下載Demo

Androidclient和server第一種方法端資料交換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.