Browse » Home » Resource, Tips » Blog article: 应用HttpURLConnection读取InputStream信息

基于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>

Tags: , ,

Posted in Resource, Tips |

Related Posts



Leave a Reply

You must be logged in to post a comment.