2024年3月13日发(作者:)
由麦可网整理,转载请注明出处
Android网络连接
在Android中,可以有多种方式来实现网络编程:
创建URL,并使用URLConnection/HttpURLConnection
使用HttpClient
使用WebView
创建URL,并使用URLConnection/HttpURLConnection
.*下面提供了访问 HTTP 服务的基本功能。使用这部分接口的基本操作主要包括:
创建 URL 以及 URLConnection / HttpURLConnection 对象
java代码:
String uriAPI = ":8751/Android/Test/API/YamWeather/";
URL objURL = new URL(uriAPI);
/* 取得连接 */
URLConnection conn = nnection();
t();
/* 将InputStream转成Reader */
BufferedReader in = new BufferedReader(new InputStreamReader(
utStream()));
String inputLine;
/* 图文件路径 */
String uriPic = "";
/* 一行一行读取 */
while ((inputLine = ne()) != null)
{
uriPic += inputLine;
}
objURL = new URL(uriPic);
/* 取得连接 */
HttpURLConnection conn2 = (HttpURLConnection) objURL
.openConnection();
t();
/* 取得返回的InputStream */
InputStream is = utStream();
/* 将InputStream变成Bitmap */
Bitmap bm = Stream(is);
/* 关闭InputStream */
();
geBitmap(bm);
/* 会将上面的网络图片显示在ImageView里面*/
复制代码
使用WebView
Android手机中内置了一款高性能webkit内核浏览器,在SDK中封装成了WebView组件。
1. webview的XML定义:
java代码:
由麦可网整理,转载请注明出处
android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> 复制代码 st文件中权限的设定: java代码: 复制代码 3.如果想要支持JavaScript: java代码: tings().setJavaScriptEnabled(true); 复制代码 4.如果不做任何处理,在显示你的Brower UI时,点击系统“Back”键,整个Browser会作为 一个整体“Back"到其他Activity中,而不是希望的在Browser的历史页面中Back。如果希望 实现在历史页面中Back,需要在当前Activity中处理Back事件:(); java代码: WebView webview; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { te(savedInstanceState); setContentView(); // 获取WebView对象 webview = (WebView) findViewById(w); // 使能JavaScript tings().setJavaScriptEnabled(true); l(""); } 复制代码 以上是采用loadUrl方法实现网页的加载,也可以采用loadData方法实现网页的加载: java代码: mWebView1 = (WebView) findViewById(iew1); /*自行设置WebView要显示的网页内容*/ mWebView1. loadData( " Subscribe to my Blog
"


发布评论