摘自:<a href="http://www.cnblogs.com/feisky/archive/2010/01/13/1646919.html">http://www.cnblogs.com/feisky/archive/2010/01/13/1646919.html</a>
在Android中,可以有多种方式来实现网络编程:
- 创建URL,并使用URLConnection/HttpURLConnection
- 使用HttpClient
- 使用WebView
创建URL,并使用URLConnection/HttpURLConnection
java.net.*下面提供了访问 HTTP 服务的基本功能。使用这部分接口的基本操作主要包括:
- 创建 URL 以及 URLConnection / HttpURLConnection 对象
- 设置连接参数
- 连接到服务器
- 向服务器写数据
- 从服务器读取数据
源码:
try {// 创建URL对象URL url = new URL("http://t.sina.cn/fesky");// 创建URL连接URLConnection connection = url.openConnection();// 对于 HTTP 连接可以直接转换成 HttpURLConnection,// 这样就可以使用一些 HTTP 连接特定的方法,如 setRequestMethod() 等// HttpURLConnection connection// =(HttpURLConnection)url.openConnection(Proxy_yours);// 设置参数connection.setConnectTimeout(10000);connection.addRequestProperty("User-Agent", "J2me/MIDP2.0");// 连接服务器connection.connect();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}
使用HttpClient
对于HttpClient类,可以使用HttpPost和HttpGet类以及HttpResponse来进行网络连接。
使用WebView
Android手机中内置了一款高性能webkit内核浏览器,在SDK中封装成了WebView组件。
http://developer.android.com/guide/tutorials/views/hello-webview.html提供了一个简单的例子:
1. webview的XML定义:
<WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
2.Manifest文件中权限的设定:
<uses-permission android:name="android.permission.INTERNET" />
3.如果想要支持JavaScript:
webview.getSettings().setJavaScriptEnabled(true);
4.如果需要在WebView中显示网页,而不是在内置浏览器中浏览,则需要mWebView.setWebViewClient,并重写shouldOverrideUrlLoading方法。
5.如果不做任何处理,在显示你的Brower UI时,点击系统“Back”键,整个Browser会作为一个整体“Back"到其他Activity中,而不是希望的在Browser的历史页面中Back。如果希望实现在历史页面中Back,需要在当前Activity中处理Back事件:mWebView.goBack();
WebView webview;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 获取WebView对象webview = (WebView) findViewById(R.id.webview); // 使能JavaScriptwebview.getSettings().setJavaScriptEnabled(true); // 如果需要在WebView中显示网页,而不是在内置浏览器中浏览,// 则需要mWebView.setWebViewClient,并重写// shouldOverrideUrlLoading方法。webview.setWebViewClient(new WebViewClientDemo());// 加载网页webview.loadUrl("http://t.sina.cn/fesky");}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {// 按下BACK键回到历史页面中if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); return true; } return super.onKeyDown(keyCode, event);}private class WebViewClientDemo extends WebViewClient { @Override // 在WebView中而不是默认浏览器中显示页面 public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }
以上是采用loadUrl方法实现网页的加载,也可以采用loadData或者loadDataWithBaseURL方法实现网页的加载:
webview.loadData(html, “text/html”, "utf-8”);
如果html中包含中文,则需要webview.loadData(URLEncoder.encode(html,encoding), mimeType, encoding);
对于本地图片或网页的显示,可以使用loadUrl,不过Url的地址前缀为file:///,如"file:///android_asset/test.htm”。