HttpClient5 分片上传完整示例
时间: 2023-09-19 22:06:31 浏览: 213
HttpClient5 是 Apache HttpClient 的最新版本,支持 HTTP/1.1 和 HTTP/2 协议,提供了更加简洁易用的 API。以下是 HttpClient5 分片上传的完整示例:
```java
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.FileBody;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class HttpClient5Example {
private static final String UPLOAD_URL = "http://example.com/upload";
public static void main(String[] args) throws IOException {
Path path = Paths.get("path/to/file");
int chunkSize = 1024 * 1024; // 1MB
long fileSize = Files.size(path);
int chunks = (int) Math.ceil((double) fileSize / chunkSize);
// Create HTTP client
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// Create HTTP request
HttpPost httpPost = new HttpPost(UPLOAD_URL);
// Create multipart entity builder
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// Add file chunks to multipart entity
for (int i = 0; i < chunks; i++) {
long offset = i * chunkSize;
long length = Math.min(chunkSize, fileSize - offset);
Path chunkPath = Paths.get(path + ".part" + i);
Files.copy(path, chunkPath);
File chunkFile = chunkPath.toFile();
FileBody fileBody = new FileBody(chunkFile);
entityBuilder.addPart("file", fileBody);
}
// Build multipart entity
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);
// Execute HTTP request
HttpResponse response = httpClient.execute(httpPost);
// Check HTTP status code
int statusCode = response.getCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println("File uploaded successfully");
} else {
System.err.println("Failed to upload file");
}
}
}
}
```
在这个示例中,我们使用了 Apache HttpClient5 的 MultipartEntityBuilder 来构建 multipart 请求实体。我们把文件切成了多个 chunk,并且添加到 multipart 实体中。在上传完成后,我们检查了 HTTP 状态码,以确定上传是否成功。
阅读全文
相关推荐


















