Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡編程:六種網絡通信方式實例分享

編輯:關於 Android 程式設計

如今手機應用滲透到各行各業,大多數都離不開網絡,與服務器的交互在所難免。那麼 Android 中都有哪些網絡訪問方式呢?本文總結了六種常見方案並附上示例代碼。

六種網絡通信方式概覽

(1)針對 TCP/IP 的 Socket、ServerSocket;
(2)針對 UDP 的 DatagramSocket、DatagramPackage。需注意 Android 設備多為手持終端,IP 隨上網動態分配並非固定,開發時與普通互聯網應用略有差異;
(3)針對 URL 的 HttpURLConnection;
(4)Google 集成 Apache HTTP 客戶端,可用於 HTTP 網絡編程;
(5)使用 WebService,可透過 jackson 支持 Xmlrpc 和 Jsonrpc,也可用 Ksoap2 實現;
(6)直接使用 WebView 組件顯示網頁,其底層為基於 chrome-lite 的瀏覽器。

一、Socket 與 ServerSocket(客戶端)

public class TestNetworkActivity extends Activity implements OnClickListener{
 private Button connectBtn;
 private Button sendBtn;
 private TextView showView;
 private EditText msgText;
 private Socket socket;
 private Handler handler;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.test_network_main);
  connectBtn = (Button) findViewById(R.id.test_network_main_btn_connect);
  sendBtn = (Button) findViewById(R.id.test_network_main_btn_send);
  showView = (TextView) findViewById(R.id.test_network_main_tv_show);
  msgText = (EditText) findViewById(R.id.test_network_main_et_msg);
  connectBtn.setOnClickListener(this);
  sendBtn.setOnClickListener(this);
  handler = new Handler(){
   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    String data = msg.getData().getString("msg");
    showView.setText("來自服務器的消息:" + data);
   }
  };
 }
 @Override
 public void onClick(View v) {
  if (v == connectBtn) { connectServer(); }
  if (v == sendBtn) { String msg = msgText.getText().toString(); send(msg); }
 }
 public void connectServer(){
  try {
   socket = new Socket("192.168.1.100", 4000);
   recevie();
  } catch (Exception e) { e.printStackTrace(); }
 }
 public void send(String msg){
  try {
   PrintStream ps = new PrintStream(socket.getOutputStream());
   ps.println(msg);
   ps.flush();
  } catch (IOException e) { e.printStackTrace(); }
 }
 public void recevie(){
  new Thread(){
   public void run(){
    while(true){
     try {
      InputStream is = socket.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String str = br.readLine();
      Message message = new Message();
      Bundle bundle = new Bundle();
      bundle.putString("msg", str);
      message.setData(bundle);
      handler.sendMessage(message);
     } catch (IOException e) { e.printStackTrace(); }
    }
   }
  }.start();
 }
}

這裡有一個關鍵點:網絡讀取放在子線程中執行,並透過 Handler 將結果回傳到主線程更新 UI,避免阻塞主線程。

二、URL、URLConnection、HttpURLConnection、Apache Http、WebView

public class TestURLActivity extends Activity implements OnClickListener {
 private Button connectBtn, urlConnectionBtn, httpUrlConnectionBtn, httpClientBtn;
 private ImageView showImageView;
 private TextView showTextView;
 private WebView webView;
 @Override
 public void onClick(View v) {
  // 直接使用 URL 對象連接
  if (v == connectBtn) {
   try {
    URL url = new URL("https://192.168.1.100:8080/myweb/image.jpg");
    InputStream is = url.openStream();
    Bitmap bitmap = BitmapFactory.decodeStream(is);
    showImageView.setImageBitmap(bitmap);
   } catch (Exception e) { e.printStackTrace(); }
  }
  // 使用 URLConnection 連接
  if (v == urlConnectionBtn) {
   try {
    URL url = new URL("https://192.168.1.100:8080/myweb/hello.jsp");
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();
    byte[] bs = new byte[1024];
    int len = 0; StringBuffer sb = new StringBuffer();
    while ((len = is.read(bs)) != -1) { sb.append(new String(bs, 0, len)); }\br>
    showTextView.setText(sb.toString());
   } catch (Exception e) { e.printStackTrace(); }
  }
  // 使用 HttpURLConnection 連接
  if (v == httpUrlConnectionBtn) {
   try {
    URL url = new URL("https://192.168.1.100:8080/myweb/hello.jsp?username=abc");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { showTextView.setText(connection.getResponseMessage()); }
   } catch (Exception e) { e.printStackTrace(); }
  }
  // 使用 Apache HttpClient 連接(重要)
  if (v == httpClientBtn) {
   try {
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("https://192.168.1.100:8080/myweb/hello.jsp");
    List dataList = new ArrayList();
    dataList.add(new BasicNameValuePair("username", "aaaaa"));
    dataList.add(new BasicNameValuePair("pwd", "123"));
    httpPost.setEntity(new UrlEncodedFormEntity(dataList));
    HttpResponse httpResponse = client.execute(httpPost);
    HttpEntity entity = httpResponse.getEntity();
    String content = EntityUtils.toString(entity);
    webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
   } catch (Exception e) { e.printStackTrace(); }
  }
 }
}

三、使用 WebService

public class LoginActivity extends Activity implements OnClickListener{
 private Button loginBtn;
 private static final String SERVICE_URL = "https://192.168.1.100:8080/loginservice/LoginServicePort";
 private static final String NAMESPACE = "https://service.lovo.com/";
 @Override
 public void onClick(View v) {
  if (v == loginBtn) {
   HttpTransportSE httpSE = new HttpTransportSE(SERVICE_URL);
   SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
   SoapObject soapObject = new SoapObject(NAMESPACE, "validate");
   soapObject.addProperty("arg0", "abc");
   soapObject.addProperty("arg1", "123");
   envelop.bodyOut = soapObject;
   try {
    httpSE.call(null, envelop);
    SoapObject resultObj = (SoapObject) envelop.bodyIn;
    String returnStr = resultObj.getProperty("return").toString();
    Toast.makeText(this, "返回值:" + returnStr, Toast.LENGTH_LONG).show();
   } catch (Exception e) { e.printStackTrace(); }
  }
 }
}

以上六種方式各有適用場景:Socket 適合長連接與實時通信,HTTP 系列適合常規的請求響應,WebService 則適合與企業級服務對接。實際開發中應根據需求靈活選用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved