All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.cosycode.ext.web.http.MyHttpDownloadResponseHandler Maven / Gradle / Ivy

Go to download

扩展模块, 用于存放一些非常用的工具或模块的扩展类, 例如在poi基础上扩展的excel的导入模块, 模拟按键模块

The newest version!
package com.github.cosycode.ext.web.http;

import com.github.cosycode.common.util.io.FileSystemUtils;
import com.github.cosycode.ext.se.util.JsonUtils;
import lombok.Data;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;

import java.io.*;
import java.nio.file.Files;

/**
 * Description : 
 * 

* created in 2023/5/14 *

* * @author CPF **/ public class MyHttpDownloadResponseHandler implements HttpClientResponseHandler { private final String savePath; public MyHttpDownloadResponseHandler(String savePath) { this.savePath = savePath; } @Override public MyHttpResponse handleResponse(ClassicHttpResponse response) throws IOException { int responseCode = response.getCode(); HttpEntity entity = response.getEntity(); DownloadResponse downloadResponse = new DownloadResponse(); downloadResponse.setFilePath(savePath); downloadResponse.setFileLength(entity.getContentLength()); downloadResponse.setStartTime(System.nanoTime()); downloadResponse.setMessage("start downloading"); File file = new File(savePath); FileSystemUtils.insureFileDirExist(file.getParentFile()); try (InputStream inputStream = entity.getContent(); OutputStream outputStream = Files.newOutputStream(file.toPath())) { byte[] buffer = new byte[1024 * 64]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); downloadResponse.addWriteLength(bytesRead); } } downloadResponse.setMessage("download success"); downloadResponse.setEndTime(System.nanoTime()); return new MyHttpResponse(responseCode, JsonUtils.toJson(downloadResponse)); } @Data public static class DownloadResponse { String contentType; long startTime; long endTime; String message; String filePath; long fileLength; long writeLength; private void addWriteLength(int length) { writeLength += length; } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy