HttpPost java上传文件封装方法
时间: 2023-11-04 12:03:33 浏览: 84
以下是一个简单的封装方法,可以用于上传单个文件:
```java
public static String uploadFile(String url, File file) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(file));
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
} finally {
response.close();
}
}
```
其中,`url` 为上传的目标地址,`file` 为待上传的文件对象。这个方法使用了 Apache HttpClient 和 MultipartEntityBuilder 来构建一个包含文件的 multipart/form-data 请求体,并发送到目标地址。上传成功后,返回服务器的响应内容(假设为字符串类型)。
阅读全文