-
HttpURLConnection 读取网络文件 7步
1 创建URL对象
2 获取HttpURLConnection
3 设置Connection属性
4 获取网络文件输入流
5 读取流
6 关闭输入流
7 关闭Connection
String strUrl = "http://192.168.0.1:12321/hfs/book/jsj.pdf";
OutputStream out = null;
InputStream in = null;
HttpURLConnection connection = null;
try {
//1. create URL Object
URL url = new URL(strUrl);
//2. obtain HttpURLConnection Object
connection = (HttpURLConnection) url.openConnection();
//3. Set connection Property
connection.setRequestMethod("GET");
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
//4. obtain InputStream
in = connection.getInputStream();
out = new FileOutputStream("D:\\jsj.pdf");
int len = -1;
byte[] buff = new byte[1024];
//5. read stream
while ((len = in.read(buff)) != -1)
{
out.write(buff, 0, len);
}
}catch (Exception e)
{
e.printStackTrace();
}
finally {
if (in != null)
{
try {
//6. clse stream
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
in = null;
}
if (out != null)
{
try {
//clse stream
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
out = null;
}
if (connection != null)
{
//7. disconnect connection
connection.disconnect();
}
}