在写HTTPClient请求的时候,明明请求成功了,但是不知道为什么报错
@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());改成一行就解决了
|