Android-通过URL获取网络资源
转载http://blog.163.com/023_dns/blog/static/11872736620129290274346/
1、先在AndroidManifest.xml中注册加入访问因特网服务的权限:
<uses-permission android:name="android.permission.INTERNET" />
(若不加入,则会出现permission denied异常)
2、代码如下:
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