Android 网络连接处理 学习笔记

Android中,可以有多种方式来实现网络编程:

* 创建URL,并使用URLConnection/HttpURLConnection
* 使用HttpClient
* 使用WebView

创建URL,并使用URLConnection/HttpURLConnection

java.net.*下面提供了访问 HTTP 服务的基本功能。使用这部分接口的基本操作主要包括:

* 创建 URL 以及 URLConnection / HttpURLConnection 对象
* 设置连接参数
* 连接到服务器
* 向服务器写数据
* 从服务器读取数据

源码:
  1. try {
  2. // 创建URL对象
  3. URL url = new URL("http://t.sina.cn/fesky");
  4. // 创建URL连接
  5. URLConnection connection = url.openConnection();
  6. // 对于 HTTP 连接可以直接转换成 HttpURLConnection,
  7. // 这样就可以使用一些 HTTP 连接特定的方法,如 setRequestMethod() 等
  8. // HttpURLConnection connection
  9. // =(HttpURLConnection)url.openConnection(Proxy_yours);
  10. // 设置参数
  11. connection.setConnectTimeout(10000);
  12. connection.addRequestProperty("User-Agent", "J2me/MIDP2.0");
  13. // 连接服务器
  14. connection.connect();
  15. } catch (IOException e) {
  16. // TODO Auto-generated catch block
  17. e.printStackTrace();
  18. }
复制代码
使用HttpClient

对于HttpClient类,可以使用HttpPost和HttpGet类以及HttpResponse来进行网络连接。



使用WebView

Android手机中内置了一款高性能webkit内核浏览器,在SDK中封装成了WebView组件

http://developer.android.com/guide/tutorials/views/hello-webview.html提供了一个简单的例子:

1. webview的XML定义:
  1. <WebView
  2. android:id="@+id/webview"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. />
复制代码
2.Manifest文件中权限的设定:
  1. <uses-permission android:name="android.permission.INTERNET" />
复制代码
3.如果想要支持JavaScript:
  1. webview.getSettings().setJavaScriptEnabled(true);
复制代码

原文地址:https://www.cnblogs.com/csj007523/p/2050973.html