HttpClient上传文件传入MultipartFile类型

通常我们在使用httpclient的时候,一把都是使用get或者postd的方式传输一些数据。在近期的项目中有这样的一个需求,我需要通过httpclient去调用一个写好的文件上传的接口,接口中是使用MultipartFile 来接受文件类型参数的。在这种情况下我们就开辟一个HttpClient中的高级功能了。直接上代码,封装了一个工具类:

 

 /**
     * 使用httpclint 发送文件
     * @author: qingfeng
     * @date: 2019-05-27
     * @param file
     *            上传的文件
     * @return 响应结果
     */
    public static String uploadFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            //添加header
            for (Map.Entry<String, String> e : headerParams.entrySet()) {
                httpPost.addHeader(e.getKey(), e.getValue());
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

 

要注意,这种情况下,一旦对方返回的结果中存在中文有可能出现乱码,解决方法就是向上面的代码中加入:

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题、

解决浏览器兼容问题。 这样就可以顺利得到返回值了

调用案例:

 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 List<MultipartFile> files = multipartRequest.getFiles("repayFile");//从request中获取前端穿过来的文件

//调用httpclient
 String res = HttpUtil.uploadFile("localhost:8080/upload", files.get(0), "repayFile", headers, paramMap);

 

上传文件的接口:

@RequestMapping(value = "/upload", method = {RequestMethod.POST })
	public void fileBatchRepay(
			@RequestParam(value = "repayFile") MultipartFile repayFile,
			@RequestParam(value = "type") String type) {
		Map<String, Object> result = new HashMap<String, Object>();
		List<List<String>> list=new ArrayList<List<String>>();
	    try {
			list = borrowRepayService.fileBatchRepay(repayFile,type);
	    	String title = "exel模板demo";
	    	RepayExcelModel report = new RepayExcelModel();
			String fileName = report.saveExcelByList(list, title, repayFile.getOriginalFilename(),request);
	    	result.put(Constant.RESPONSE_DATA, "/down.htm?path="+fileName);
	    	result.put(Constant.RESPONSE_CODE, Constant.SUCCEED_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, "获取成功");
		} catch (BussinessException e) {
			logger.error(e.getMessage(),e);
			result.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			result.put(Constant.RESPONSE_CODE, Constant.FAIL_CODE_VALUE);
			result.put(Constant.RESPONSE_CODE_MSG, "失败");
		}
	    ServletUtils.writeToResponse(response, result);
	}

 

好了,就分享到这里,希望对大家有帮助

想学java的同学,也可以看我的java基础教学视频https://www.bilibili.com/video/av37413483?from=search&seid=16996396768466285203,免费学习

 

 

 

 

  • 7
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 26
    评论
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值