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("/uploads/allimg/201110/20111011155434348.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.2cto.com
while((len = inSream.read(buffer)) != -1 ){
outStream.write(buffer,0, len);
}
outStream.close();
inSream.close();
}
摘自:com360 博客
相关新闻>>
- 发表评论
-
- 最新评论 更多>>