2024年3月21日发(作者:)
HttpURLConnection对象
1.从Internet获取网页,发送请求,将网页以流的形式读回来.
步骤:
1)创建一个URL对象:URL url = new URL( );
2)利用HttpURLConnection对象从网络中获取网页数据:HttpURLConnection conn
= (HttpURLConnection) nnection();
3)设置连接超时:nectTimeout(6*1000);
4)对响应码进行判断:if (ponseCode() != 200) throw new
RuntimeException("请求url失败");
5)得到网络返回的输入流:InputStream is = utStream();
6)String result = readData(is, "GBK");
7)nect();
总结:
--记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操
作.
--返回的响应码200,是成功.
--利用ByteArrayOutputStream类,将得到的输入流写入内存.
--在Android中对文件流的操作和JAVA SE上面是一样的.
2.从Internet获取文件
利用HttpURLConnection对象,从网络中获取文件数据.
步骤:
1)创建URL对象,并将文件路径传入:URL url = new
URL(/20100125/ );
2)创建HttpURLConnection对象,从网络中获取文件数据:HttpURLConnection
conn = (HttpURLConnection)
nnection();
3)设置连接超时:nectTimeout(6* 1000);
4)对响应码进行判断:if (ponseCode() != 200) throw new
RuntimeException("请求url失败");
5)得到网络返回的输入流:InputStream is = utStream();


发布评论