首页 > 代码库 > Android-通过URL获取网络资源
Android-通过URL获取网络资源
1、先在AndroidManifest.xml中注册加入访问因特网服务的权限:
<uses-permission android:name="android.permission.INTERNET" />
(若不加入,则会出现permission denied异常)
2.
1 package vip.test.HttpGet; 2 import java.io.BufferedInputStream; 3 import java.io.InputStream; 4 import java.net.URL; 5 import java.net.URLConnection; 6 import org.apache.http.util.ByteArrayBuffer; 7 import org.apache.http.util.EncodingUtils; 8 import vip.test.HttpGet.R; 9 import android.app.Activity;10 import android.os.Bundle;11 import android.widget.TextView;12 public class HttpGet extends Activity {13 /** Called when the activity is first created. */14 @Override15 public void onCreate(Bundle savedInstanceState) {16 super.onCreate(savedInstanceState);17 setContentView(R.layout.main);18 TextView tv = new TextView(this);19 String myString = null;20 try {21 // 定义获取文件内容的URL22 URL myURL = new URL(23 "HTTP://www.baidu.com/hello.txt"");24 // 打开URL链接25 URLConnection ucon = myURL.openConnection();26 // 使用InputStream,从URLConnection读取数据27 InputStream is = ucon.getInputStream();28 BufferedInputStream bis = new BufferedInputStream(is);29 // 用ByteArrayBuffer缓存30 ByteArrayBuffer baf = new ByteArrayBuffer(50);31 int current = 0;32 while ((current = bis.read()) != -1) {33 baf.append((byte) current);34 }35 // 将缓存的内容转化为String,用UTF-8编码36 myString = EncodingUtils.getString(baf.toByteArray(), "UTF-8");37 } catch (Exception e) {38 myString = e.getMessage();39 }40 // 设置屏幕显示41 tv.setText(myString);42 this.setContentView(tv);43 }44 }
3、代码解释:
1)实例URL类:myURL,表示要获取内容的网址:
URL myURL=new URL(HTTP://www.baidu.com/hello.txt);
2)实例URLConnection类,表示一个打开的网络连接ucon:
URLConnection ucon=myURL.openConnection();
3)用字节流的形式表示从网络上读到的数据:
InputStream is=ucon.getInputStream();
为避免频繁读取字节流,提高读取效率,用BufferedInputStream缓存读到的字节流
InputStream is=ucon.getInputStream();
BufferedInputStream bis=new BufferedInputStream(is);
4)用read方法读入网络数据:
ByteArrayBuffer baf=new ByteArrayBuffer(50);
int current=0;
while((current=bis.read())!=-1)
{
baf.append((byte)current);
}
5)由于读到的数据只是字节流,无法直接显示到屏幕上,所以得在显示之前将字节流转换为可读取的字符串:
myString=EncodingUtils.getString(baf.toByteArray(),"UTF-8");
(如果读取的是.txt等文件是UTF-8格式的,就需要对数据进行专门的转换)
Android-通过URL获取网络资源