httpclient发送文件及json参数

maven,jar


    commons-httpclient
    commons-httpclient
    3.1


    org.apache.httpcomponents
    httpmime
    4.5.3

 单个文件发送

/**
	 * 发送图片HttpPost请求
	 * @param url
	 * @param headers 头部参数
	 * @param body body参数,json字符串
	 * @return
	 */
	public static String sendFilePost(String url, Map headers, String body,InputStream inputStream) {
		CloseableHttpClient httpclient = createHttpClient();
		HttpPost httppost = new HttpPost(url);
		if(inputStream==null){

		}
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			//第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
			//第三个参数是文件名
			//3)
			builder.addBinaryBody("file", inputStream, ContentType.create("multipart/form-data"), "2.jpg");
			//4)构建请求参数 普通表单项
		/*	StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
			builder.addPart("id", stringBody);*/
		//决中文乱码
		ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE,Consts.UTF_8);
		builder.addTextBody("json", body, contentType);
		HttpEntity entity = builder.build();
		if (null!=headers&&headers.size()>0){
			for (Map.Entry entry : headers.entrySet()) {
				httppost.addHeader(entry.getKey(),entry.getValue());
			}
		}
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			httppost.setConfig(requestConfig);
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			logger.error("请求出错:" + url, e);
			return null;
		}
		String result = null;
		try {
			if(response!=null){
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null && response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK) {// 判断请求状态
					result = EntityUtils.toString(httpEntity);
				}
			}
		} catch (Exception e) {
			logger.error("请求出错:" + url, e);
		} finally {
			try {
				if(response!=null){
					response.close();
				}
			} catch (IOException e) {
				logger.error("请求出错:" + url, e);
			}
		}
		logger.info("请求的URL:" + url + ", 返回结果:" + result);
		return result;
	}

 单个文件发送:

        String body =ParseJson.toJSONString(user);
        InputStream inputStream = null;
        try {
            inputStream = pic.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String res =HttpClientUtil.sendFilePost("http://localhost:8080/third/accept",null,body,inputStream);

 单个文件接收

 @RequestMapping(value = "/accept", method = RequestMethod.POST)
    @ResponseBody
    public Result getPost(@RequestParam(value = "file") MultipartFile pic,@RequestParam(value = "json") String json) {
    }

多个文件方法:

/**
	 * HttpClient post multipart/form-data数据实现多文件上传
	 * @param url
	 * @param headers 头部参数
	 * @param body body参数,json字符串
	 * @param multipartFiles 文件列表
	 * @param fileParName 接收的文件名
	 * @return
	 */
	public static String sendFilePost(String url, Map headers, String body,List multipartFiles,String fileParName) {
		CloseableHttpClient httpclient = createHttpClient();
		HttpPost httppost = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
		//单个文件
		String fileName = null;
		MultipartFile multipartFile = null;
		for (int i = 0; i < multipartFiles.size(); i++) {
			//第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
			//第三个参数是文件名
			//3)
			multipartFile = multipartFiles.get(i);
			fileName = multipartFile.getOriginalFilename();
			InputStream inputStream = null;
			try {
				inputStream = multipartFile.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
			builder.addBinaryBody(fileParName,inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
		}
		//4)构建请求参数 普通表单项
		/*	StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
			builder.addPart("id", stringBody);*/
		//决中文乱码
		ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE,Consts.UTF_8);
		builder.addTextBody("json", body, contentType);
		HttpEntity entity = builder.build();
		if (null!=headers&&headers.size()>0){
			for (Map.Entry entry : headers.entrySet()) {
				httppost.addHeader(entry.getKey(),entry.getValue());
			}
		}
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			httppost.setConfig(requestConfig);
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			logger.error("请求出错:" + url, e);
			return null;
		}
		String result = null;
		try {
			if(response!=null){
				HttpEntity httpEntity = response.getEntity();
				if (httpEntity != null && response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK) {// 判断请求状态
					result = EntityUtils.toString(httpEntity);
				}
			}
		} catch (Exception e) {
			logger.error("请求出错:" + url, e);
		} finally {
			try {
				if(response!=null){
					response.close();
				}
			} catch (IOException e) {
				logger.error("请求出错:" + url, e);
			}
		}
		logger.info("请求的URL:" + url + ", 返回结果:" + result);
		return result;
	}

1.发送,fileList为List fileList,file为接收方文件参数

String res =HttpClientUtil.sendFilePost("http://localhost:8080/third/accept",null,body,fileList,"file");

 

2.接收方

   @RequestMapping(value = "/accept", method = RequestMethod.POST)
    @ResponseBody
    public String getPost(@RequestParam(value = "file") List pic,@RequestParam(value = "json") String json) {}

 

你可能感兴趣的:(工具)