使用HttpClients发送带文件的post请求网上代码不少,我主要是遇到了一个无法接收到请求的问题。后来试了很多方法发现是RequestBody这个注解的问题,去掉这个注解就好了。这么简单的问题,有时候就是容易忽略,特意记一下吧。
顺便贴一下我的发送请求的代码吧。
File file = new File(fullPath);
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(),file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),fileInputStream);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(FilePushSet.PUSHURL.getMsg());
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = multipartFile.getOriginalFilename();
// 文件流
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//表单中其他参数,如果没有其他参数可以注释该部分
builder.addPart("md5",new StringBody(FilePushSet.MD5.getMsg(), ContentType.create("text/plain", Consts.UTF_8)));
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回
String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
因为一开始想的是需要转换成MultipartFile,其实不转换,在builder.addBinaryBody这里直接使用文件输入流也是可以的,但是懒得再去改了。