分块下载文件示例
示例场景
本文介绍如何通过数据管理API代理器方式,对某个实体的实例化数据进行分块下载文件。
前提条件
安装数据管理API代理器时,已引入“file-download-sdk-1.0.0-SNAPSHOT”JAR包和添加相关依赖。
操作步骤
参考如下示例调用FileDownloader接口,分块下载test.zip文件。
// 自动注入DelegatorConfig配置对象
@Autowired
private DelegatorConfig config;
// 自动注入XdmTokenService服务对象
@Autowired
XdmTokenService xdmTokenService;
/**
* 文件分片下载
*
* @throws IOException I/O异常
* @throws ExecutionException 并发异常
* @throws InterruptedException 线程中断异常
*/
@Test
public void testDownLoadFile() throws IOException, ExecutionException, InterruptedException {
HttpClient httpClient = defaultHttpClient(); // 获取默认的apache httpclient客户端
URL preSignedUrl = getPreSignedUrl(httpClient); // 获取预签名URL
FileDownloader fileDownloader = new FileDownloader(); // 创建一个FileDownloader实例
FileDescriptor fileDescriptor = new ObjectStorageFileDescriptor(preSignedUrl, httpClient); // 使用预签名URL创建一个FileDescriptor对象
File file = new File("D:/work/Demo/" + fileDescriptor.getFileName()); // 定义要保存文件的目标路径
Future<File> download = fileDownloader.download(fileDescriptor, 5, 200 * 1024 * 1024, file); // 下载文件并返回一个Future对象
download.get();
boolean done = download.isDone(); // 检查下载是否完成
System.out.println(done);
}
/**
* 获取预签名URL的方法。
*
* @param httpClient HttpClient实例
* @return 返回预签名URL
* @throws IOException 如果发生I/O错误
*/
private URL getPreSignedUrl(HttpClient httpClient) throws IOException {
// 构建基础URL
String url = String.format(Locale.ROOT, "%s/%s/services/%s/%s", this.config.getDomain(), this.config.getSubAppId(), "rdm/basic/api/v2/file", "downloadFile");
// 添加查询参数构建完整的URL模板
String urlTemplate = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("model_name", "yourModelName")
.queryParam("model_number", "yourModelNumber")
.queryParam("instance_id", "yourInstanceId")
.queryParam("application_id", "yourApplicationId")
.queryParam("is_master_attr", "yourIsMasterAttr")
.queryParam("attribute_name", "yourAttributeName")
.queryParam("file_ids", "yourFileIds")
.queryParam("download_type", "OUTBOUND_LINK")
.queryParam("tenant_id", new Object[] {"yourTenantId"})
.encode()
.toUriString();
URL downloadUrl = new URL(urlTemplate); // 创建URL对象
HttpGet httpGet = new HttpGet(downloadUrl.toString()); // 创建HttpGet请求
httpGet.addHeader("X-AUTH-TOKEN", this.xdmTokenService.getToken()); // 设置请求头
HttpResponse execute = httpClient.execute(httpGet); // 执行请求并获取响应
return new URL(execute.getFirstHeader("Location").getValue()); // 从响应中获取重定向地址作为预签名URL
}
/**
* 支持的加密套件列表。
*/
private static final List<String> SUPPORTED_CIPHER_SUITES = Collections.unmodifiableList(
Arrays.asList("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"));
/**
* 创建默认的HttpClient实例。
*
* @return 返回HttpClient实例
*/
public HttpClient defaultHttpClient() {
try {
// 创建SSL上下文
SSLContext sslContext = (new SSLContextBuilder()).setSecureRandom(SecureRandom.getInstanceStrong())
.loadTrustMaterial((KeyStore) null, (chain, authType) -> {
return true;
})
.build();
// 创建SSL连接套接字工厂
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, new String[] {"TLSv1.2"},
(String[]) SUPPORTED_CIPHER_SUITES.toArray(new String[0]), NoopHostnameVerifier.INSTANCE);
RequestConfig requestConfig =
RequestConfig.custom().setSocketTimeout(300000).setConnectTimeout(20000).build();
// 创建请求配置
return HttpClients.custom()
.disableRedirectHandling()
.setDefaultRequestConfig(requestConfig)
.setConnectionTimeToLive(20L, TimeUnit.SECONDS)
.setMaxConnPerRoute(40)
.setSSLSocketFactory(sslConnectionSocketFactory)
.setMaxConnTotal(120)
.build();
} catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException var3) {
GeneralSecurityException e = var3;
throw new DownloadException(e);
}
}