HttpPost InputStream 上传文件封装方法
时间: 2024-01-17 21:03:23 浏览: 124
文件上传的封装
以下是一个封装方法,可以实现通过HttpPost上传文件:
```java
public static String postFile(String url, File file) throws IOException {
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
HttpEntity entity = builder.build();
post.setEntity(entity);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败,状态码为:" + statusCode);
}
HttpEntity responseEntity = response.getEntity();
String result = EntityUtils.toString(responseEntity);
EntityUtils.consume(entity);
EntityUtils.consume(responseEntity);
response.close();
client.close();
return result;
}
```
使用方法:
```java
File file = new File("/path/to/file");
String url = "http://example.com/upload";
String result = postFile(url, file);
System.out.println(result);
```
其中,`url` 是上传接口的地址,`file` 是要上传的文件对象,`result` 是服务器返回的响应字符串。
阅读全文