1、先在AndroidManifest.xml中注册加入访问因特网服务的权限:
<uses-permission android:name="android.permission.INTERNET" />
(若不加入,则会出现permission denied异常)
2、代码如下:
Java代码
package vip.test.HttpGet;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;
import vip.test.HttpGet.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpGet extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
String myString = null;
try {
// 定义获取文件内容的URL
URL myURL = new URL(
"HTTP://www.baidu.com/hello.txt"");
// 打开URL链接
URLConnection ucon = myURL.openConnection();
// 使用InputStream,从URLConnection读取数据
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// 用ByteArrayBuffer缓存
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// 将缓存的内容转化为String,用UTF-8编码
myString = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
} catch (Exception e) {
myString = e.getMessage();
}
// 设置屏幕显示
tv.setText(myString);
this.setContentView(tv);
}
}
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格式的,就需要对数据进行专门的转换)