基于Android平台的应用开发大部分都会涉及到应用网络资源,然而通过指定的URL来读取数据可以算得上是最基本的应用。下面通过一个小例子演示如何实现这个方法。
注意:在调试代码之前,请首先确认AndroidManifest中已经添加了Internet permission标签。
源代码:
private void getConnStream(){
String result = null;
URL url = null;
try {
url = new URL("http://www.androidres.com");
} catch (MalformedURLException e) {
Log.e("TestConnStream_URL",e.getMessage());
}
if (url != null) {
try {
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
String inputLine;
int lineCount = 0; // limit the lines for the example
while ((lineCount < 8 ) && ((inputLine = in.readLine()) != null)) {
lineCount++;
result += "n" + inputLine;
}
in.close();
urlConn.disconnect();
} catch (IOException e) {
Log.e("TestConnStream",e.getMessage());
}
}
}
返回的result结果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Android Resource | Android 资源 - 资讯 - 教程 |</title>
<link rel="stylesheet" href="http://www.androidres.com/wp-content/themes/BobV3/style.css" type="text/css" media="screen" />
<link rel="alternate" type="application/rss+xml" title="Android Resource | 资源 资讯 教程 RSS Feed" href="http://www.androidres.com/?feed=rss2" />
<link rel="pingback" href="http://www.androidres.com/xmlrpc.php" />
<script type="text/javascript" language="javascript" src="http://www.androidres.com/wp-content/themes/BobV3/moo.js"></script>
<script type="text/javascript" language="javascript" src="http://www.androidres.com/wp-content/themes/BobV3/moostick.js"></script>
This entry was posted
on Thursday, April 30th, 2009 at 2:49 pm and is filed under Resource, Tips.
You can follow any responses to this entry through the comments feed.
You can leave a response, or trackback from your own site.
Tags: BufferedReader, HttpURLConnection, InputStream
Posted in Resource, Tips |
Related Posts
Leave a Reply
You must be logged in to post a comment.