public class GetHtmlCodeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView = (TextView)this.findViewById(R.id.picture_textview);
try {
textView.setText(getPictureData("
http://www.baidu.com"));
} catch (Exception e) {
Log.e("GetHtmlCodeActivity", e.toString());
Toast.makeText(GetHtmlCodeActivity.this, "网络连接失败", 1).show();
}
}
//得到图片的二进制数据
public String getPictureData(String path) throws Exception{
// 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
URL url = new URL("
http://www.baidu.com/");
// 每个 HttpURLConnection 实例都可用于生成单个请求,
//但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置 URL 请求的方法
conn.setRequestMethod("GET");
//设置一个指定的超时值(以毫秒为单位),
//该值将在打开到此 URLConnection 引用的资源的通信链接时使用。
conn.setConnectTimeout(5 * 1000);
// conn.getInputStream()返回从此打开的连接读取的输入流
InputStream inStream = conn.getInputStream();// 通过输入流获取html数据
byte[] data = readInputStream(inStream);// 得到html的二进制数据
String html = new String(data);
return html;
}
//读取输入流中的数据,返回字节数组byte[]
public byte[] readInputStream(InputStream inStream) throws Exception{
//此类实现了一个输出流,其中的数据被写入一个 byte 数组
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// 字节数组
byte[] buffer = new byte[1024];
int len = 0;
//从输入流中读取一定数量的字节,并将其存储在缓冲区数组buffer 中
while ((len = inStream.read(buffer)) != -1) {
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
outStream.write(buffer, 0, len);
}
inStream.close();
//toByteArray()创建一个新分配的 byte 数组。
return outStream.toByteArray();
}
}
可以看一下这个自己想想哦