在写HTTPClient请求的时候,明明请求成功了,但是不知道为什么报错
/**
*
* @param file 文件
* @param url 请求到哪里url http://127.0.0.1:8080/upload
* @param target 上传到哪里 e:/test/
* @return
* @throws IOException
*/
@PostMapping("/test")
@ResponseBody
private String gettesthttpclient1(MultipartFile file,String url,String target) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(10000)
.setConnectTimeout(5000)
.build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// 解决中文文件名乱码问题
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setCharset(Consts.UTF_8);
InputStream inputStream = file.getInputStream();
//设置文件
entityBuilder.addBinaryBody("file", inputStream, ContentType.DEFAULT_BINARY, file.getOriginalFilename());
//设置参数
entityBuilder.addTextBody("target", target, ContentType.create("text/plain", Charset.forName("UTF-8")));
httpPost.setEntity(entityBuilder.build());
httpPost.setConfig(requestConfig);
HttpResponse httpResponse = httpclient.execute(httpPost);
String flag = EntityUtils.toString(httpResponse.getEntity());
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
return flag;
}
原因分析:
HttpResponse httpResponse = httpclient.execute(httpPost);
String flag = EntityUtils.toString(httpResponse.getEntity());
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
return flag;
EntityUtils.toString(httpResponse.getEntity())方法中操作的是流数据,流数据是一次性数据所以同一个HttpEntity不能使用多次该方法.
return EntityUtils.toString(httpclient.execute(httpPost).getEntity());改成一行就解决了