HttpClient POST 上传文件传入MultipartFile类型

静态方法

/**
	 * post请求接口
	 * 
	 * @param url
	 * @param imageUploadFileName
	 * @param file
	 * @param headerParams
	 * @param otherParams
	 * @param timeout
	 *            秒
	 * @return
	 */
	public static String postResultMultipartFile(String url, String imageUploadFileName, MultipartFile file,
			Map headerParams, Map otherParams, int timeout)
	{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result = "";
		HttpEntity httpEntity = null;
		HttpEntity responseEntity = null;
		try
		{
			String fileName = file.getOriginalFilename();
			HttpPost httpPost = new HttpPost(url);
			//添加header
			for (Map.Entry 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(imageUploadFileName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA,
				fileName);// 文件流
			// 添加param
			for (Map.Entry e : otherParams.entrySet())
			{
				builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
			}
			httpEntity = builder.build();
			httpPost.setEntity(httpEntity);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * timeout)
					.setConnectTimeout(1000 * timeout).build();//设置请求时间
			httpPost.setConfig(requestConfig);
			HttpResponse response = httpClient.execute(httpPost);// 执行提交
			responseEntity = response.getEntity();
			if(responseEntity != null)
			{
				// 将响应内容转换为字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
			}
		}
		catch (Exception e)
		{
			Logger.info("postResultMultipartFile", e);
			e.printStackTrace();
		}
		return result;
	}

调用静态方法示例

Map otherParams = new HashMap();
Map headerParams = new HashMap();
otherParams.put("phone", phone);
String assistResult = DcHttpClientUtils.postResultMultipartFile(serverUrl, "img", img, headerParams,otherParams, 10);

接收接口示例

    @RequestMapping(value = "/upload_imgs",method = RequestMethod.POST)
    @ResponseBody
    public JsonResultWrap uploadImgs(HttpServletRequest request, String phone,          
        @RequestParam("img")MultipartFile img )
    {

    }

 

你可能感兴趣的:(比较完整的功能)