httpclient 发送大文件
时间: 2023-11-03 17:05:03 浏览: 201
使用Apache HttpClient发送大文件可以使用MultipartEntityBuilder。这个类可以将多个part组合成multipart/form-data格式的请求实体。
下面是一个发送大文件的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://your-url.com/upload");
File file = new File("path/to/your/file");
InputStream inputStream = new FileInputStream(file);
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody("file", inputStream, ContentType.APPLICATION_OCTET_STREAM, file.getName())
.addTextBody("description", "This is a large file upload test", ContentType.create("text/plain", StandardCharsets.UTF_8))
.build();
httpPost.setEntity(httpEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
} finally {
response.close();
}
}
}
```
在此代码中,我们首先创建了一个CloseableHttpClient对象,然后创建一个HttpPost对象并设置目标URL。接下来,我们打开文件并将其添加到multipart实体中。最后,我们执行HTTP POST请求并关闭响应。
阅读全文