设为首页 加入收藏

TOP

Android 从Internet获取html,图片
2014-11-24 12:35:36 来源: 作者: 【 】 浏览:8
Tags:Android Internet 获取 html 图片

在清单文件中加上网络访问权限



利用HttpURLConnection对象,我们可以从网络中获取网页数据.


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("https://www.cppentry.com/upload_files/article/54/1_1ka9j__.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;


while((len = inSream.read(buffer)) != -1 ){


outStream.write(buffer,0, len);


}


outStream.close();


inSream.close();


}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android短信应用——短信信息实时.. 下一篇加载TQ2440驱动-Hello World 模块

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·工业机器人TCP校准中 (2025-12-25 05:19:17)
·opc 通讯协议与 TCP (2025-12-25 05:19:15)
·labview中tcp/ip通信 (2025-12-25 05:19:13)
·新书介绍《Python数 (2025-12-25 04:49:47)
·怎么利用 Python 进 (2025-12-25 04:49:45)