package com.downLoad;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* 单线程下载
*
*/
public class DownLoad {
public static final String path = "http://download.java.net/jdk/jdk-api-localizations/jdk-api-zh-cn/publish/1.6.0/chm/JDK_API_1_6_zh_CN.CHM";
public static void main(String[] args) {
// [一 ☆☆☆☆]获取服务器文件的大小 要计算每个线程下载的开始位置和结束位置
try {
// (1) 创建一个url对象 参数就是网址
URL url = new URL(path);
// (2)获取HttpURLConnection 链接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// (3)设置参数 发送get请求
conn.setRequestMethod("GET"); // 默认请求 就是get 要大写
// (4)设置链接网络的超时时间
conn.setConnectTimeout(5000);
// (5)获取服务器返回的状态码
int code = conn.getResponseCode(); // 200 代表获取服务器资源全部成功 206请求部分资源
if (code == 200) {
// (6)获取服务器文件的大小
int length = conn.getContentLength();
System.out.println("length:" + length);
InputStream in = conn.getInputStream();
File file = new File(getFilename(path));
FileOutputStream out = new FileOutputStream(file);
int len = -1;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.flush();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取文件的名字
private static String getFilename(String path) {
int start = path.lastIndexOf("/") + 1;
return path.substring(start);
}
}
HttpURLConnection 下载
最新推荐文章于 2024-03-09 23:50:11 发布