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.setDoInput(true);
- connection.setRequestMethod("POST");
-
-
-
-
-
-
- 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;
-
-
-
-
- HttpGet httpGet = new HttpGet(path);
- HttpClient httpClient = new DefaultHttpClient();
- InputStream inputStream = null;
- BufferedReader bufReader = null;
- String result = "";
-
- mHttpResponse = httpClient.execute(httpGet);
- 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;
- }
-
- }
- 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);
小提示:
对于HttpClient和HttpURLConnection我们该怎么选择呢?
在Android 2.2版本之前,由于HttpClient有较少的bug,因此我们选择它来使用。然而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择。HttpUrlConnection对大部分工作进行了包装,屏蔽了不需要的细节,体积较小,因而非常适用于Android项目。并且HttpUrlConnection直接在系统层面做了缓存策略处理,可以加快重复请求的速度。由于其压缩(GZip)和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。对于新的应用程序应该更加偏向于使用HttpURLConnection,因为在后续Google官方会将更多的时间放在优化HttpURLConnection上面。
本文转载地址:http://blog.csdn.net/wdong_love_cl/article/details/51570961