场景:后台不是以form表单形式接收上传的文件,而是从请求体中直接获取(像这样req.getInputStream())
http请求代码如下:
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = null;
HttpResponse response = null;
HttpPost httpPost = null;
try {
httpClient = HttpClientBuilder.create().build();
//设置请求参数
RequestConfig config = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
//请求地址
String url = "http://localhost:8080/xxx-core/upload?bucket=route&key=test&index=1";
httpPost = new HttpPost(url);
httpPost.setConfig(config);
//<关键步骤>将文件封装在请求体中
BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
basicHttpEntity.setContentLength(92944);
basicHttpEntity.setContent(new ByteArrayInputStream(FileUtils
.readFileToByteArray(new File("D:/tmp/hello.jpg"))));
httpPost.setEntity(basicHttpEntity);
//执行请求
response = httpClient.execute(httpPost);
//响应内容
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
}
后台获取代码如下:
<pre name="code" class="java">@RequestMapping(value = "/upload/{bucket}", method = RequestMethod.POST)
public String durativeUpload(
@PathVariable(value = "bucket") String bucket,
@RequestParam(value = "key") String key,
@RequestParam(value = "index") Integer index,
@RequestParam(value = "md5", required = false) String md5,
@RequestParam(value = "token") String token,
HttpServletRequest req, HttpServletResponse resp) throws Exception{
//请求体中获取文件
req.getInputStream();
//…………
}