Android網路通訊的實現方式_Android

來源:互聯網
上載者:User

Android網路編程分為兩種:基於http協議的,和基於socket的。
基於Http協議:HttpClient、HttpURLConnection、AsyncHttpClient架構等
基於Socket
(1)針對TCP/IP的Socket、ServerSocket
(2)針對UDP/IP的DatagramSocket、DatagramPackage
(3)Apache Mina架構
一、HttpURLConnection的實現方式

String response = null; Url url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 建立串連執行個體 connection.setConnectTimeout(20000);// 設定連線逾時時間,單位毫秒 //connection.setReadTimeout(20000);// 設定讀取資料逾時時間,單位毫秒 connection.setDoInput(true);// 是否開啟輸入資料流 true|false connection.setRequestMethod("POST");// 提交方法POST|GET //connection.setUseCaches(false);// 是否緩衝true|false //connection.setRequestProperty("accept", "*/*"); //connection.setRequestProperty("Connection", "Keep-Alive"); //connection.setRequestProperty("Charset", "UTF-8"); //connection.setRequestProperty("Content-Length", String.valueOf(data.length)); //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.connect();// 開啟串連連接埠 int responseCode = conn.getResponseCode(); BufferedReader reader = null; if (responseCode == 200) {   reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));   StringBuffer buffer = new StringBuffer();   String line = "";   while ((line = reader.readLine()) != null) {     buffer.append(line);   }   response = buffer.toString(); } else {   response = "返回碼:"+responseCode; } reader.close(); conn.disconnect(); 

二、HttpClient實現方式

HttpResponse mHttpResponse = null; HttpEntity mHttpEntity = null; //建立HttpPost對象 //HttpPost httppost = new HttpPost(path); //設定httpPost請求參數 //httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); HttpGet httpGet = new HttpGet(path);   HttpClient httpClient = new DefaultHttpClient(); InputStream inputStream = null; BufferedReader bufReader = null; String result = ""; // 發送請求並獲得響應對象 mHttpResponse = httpClient.execute(httpGet);//如果是“POST”方式就傳httppost  if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   // 獲得響應的訊息實體   mHttpEntity = mHttpResponse.getEntity();   // 擷取一個輸入資料流   inputStream = mHttpEntity.getContent();   bufReader = new BufferedReader(new InputStreamReader(inputStream));    String line = "";   while (null != (line = bufReader.readLine())) {     result += line;   }   //result = EntityUtils.toString(mHttpResponse.getEntity()); }  if (inputStream != null) {   inputStream.close(); } bufReader.close(); if (httpClient != null) {   httpClient.getConnectionManager().shutdown(); } 

三、實用AsyncHttpClient架構的實現方式

AsyncHttpClient client = new AsyncHttpClient();  client.get(url, new AsyncHttpResponseHandler() {    @Override    public void onSuccess(int i, Header[] headers, byte[] bytes) {            String response = new String(bytes, 0, bytes.length, "UTF-8");              }    @Override    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {     }  });  

四、使用WebView視圖組件顯示網頁

myWebView.getSettings().setJavaScriptEnabled(true);  myWebView.setWebViewClient(new WebViewClient() {    @Override    public boolean shouldOverrideUrlLoading(WebView view, String url) {      view.loadUrl(url);      return true;    }  });  myWebView.loadUrl("http://"+networkAddress);  

以上就是Android中網路通訊幾種方式的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.