httpclient4.3.X post请求上传,将文件封装到请求体中(不以form表单形式)

来源:互联网 发布:淘宝不能跟客服聊天 编辑:程序博客网 时间:2024/06/04 01:14

场景:后台不是以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();    //…………}

0 0
原创粉丝点击