android 从internet获取html,图片
在清单文件中加上网络访问权限
<!-- 访问internet权限-->
<uses-permissionandroid:name="android.permission.INTERNET"/>
利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = newURL("http://www.sohu.com");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is =conn.getInputStream();//得到网络返回的输入流
Stringresult = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static StringreadData(InputStream inSream, String charsetName) throws Exception{
ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();
byte[]buffer = new byte[1024];
intlen = -1;
while((len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,0, len);
}
byte[]data = outStream.toByteArray();
outStream.close();
inSream.close();
returnnew String(data, charsetName);
}
利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = newURL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is =conn.getInputStream();
readAsFile(is,"Img269812337.jpg");
public static voidreadAsFile(InputStream inSream, File file) throws Exception{
FileOutputStreamoutStream = new FileOutputStream(file);
byte[]buffer = new byte[1024];
intlen = -1; www.zzzyk.com
while((len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,0, len);
}
outStream.close();
inSream.close();
}
摘自:com360 博客
补充:移动开发 , Android ,