httpclient:与springmvc进行跨域传输,上传文件,携带参数——使用HttpPost方式

一.上传文件

1.HttpClient类

/**
	 * @param file
	 * @param url
	 */
	public static void uploadFileByHttpPost(File file, String url) {
		CloseableHttpClient client = HttpClients.custom().build();
		try {
			HttpPost post = new HttpPost(url);
			FileBody fileBody = new FileBody(file);
			/*
			 * 可以在MultipartEntityBuilder中添加多个part(ContentBody),用来传递多个参数
			 * ByteArrayBody
			 * InputStreamBody
			 * FileBody
			 * StringBody
			 */
			HttpEntity entity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
			post.setEntity(entity);
			CloseableHttpResponse resp = client.execute(post);
			int status = resp.getStatusLine().getStatusCode();
			if (status == 200) {
				Logger.getLogger(HttpClientUtil.class).info("上传成功");
			} else {
				Logger.getLogger(HttpClientUtil.class).info("上传失败");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2.controller接口

@RequestMapping(params = "uploadFile")
	public void uploadFile(@RequestParam CommonsMultipartFile file) {
		File serverFile = new File("E:/to/" + file.getOriginalFilename());
		try {
			FileUtils.writeByteArrayToFile(serverFile, file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

3.测试类

@Test
	public void uploadFileByHttpPost() {
		String url = PropUtil.configProp.getProperty("url") + "/httpClientController.do?uploadFile";
		File file = new File("E:/from/test");
		HttpClientUtil.uploadFileByHttpPost(file, url);
	}

二.上传文件并携带参数

1.HttpClient类

/**
	 * @param file
	 * @param url
	 * @param params
	 */
	public static void sendFileAndParamsByHttpPost(File file, String url, Map<String, String> params) {
		CloseableHttpClient client = HttpClients.custom().build();
		try {
			HttpPost post = new HttpPost(url);
			FileBody fileBody = new FileBody(file);
			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			for (Entry<String, String> entry : params.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
//				multipartEntityBuilder.addTextBody(key, value);
				multipartEntityBuilder.addTextBody(key, value, ContentType.TEXT_PLAIN.withCharset("utf-8"));
			}
			HttpEntity entity = multipartEntityBuilder
					.addPart("file", fileBody)
					.build();
			post.setEntity(entity);
			CloseableHttpResponse resp = client.execute(post);
			int status = resp.getStatusLine().getStatusCode();
			if (status == 200) {
				Logger.getLogger(HttpClientUtil.class).info("上传成功");
			} else {
				Logger.getLogger(HttpClientUtil.class).info("上传失败");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
注:
multipartEntityBuilder.addTextBody不设置编码可能会中文乱码

2.controller接口

@RequestMapping(params = "sendFileAndParamsByHttpPost")
	public void sendFileAndParamsByHttpPost(@RequestParam CommonsMultipartFile file, @RequestParam("userName") String username, @RequestParam String id, String sex) {
		LoggerFactory.getLogger(getClass()).info("fileName: {}, userName: {}, id: {}, sex: {}", file.getOriginalFilename(), username, id, sex);
	}

3.测试类

@Test
	public void sendFileAndParamsByHttpPost() {
		String url = PropUtil.configProp.getProperty("url") + "/httpClientController.do?sendFileAndParamsByHttpPost";
		File file = new File("E:/from/test");
		Map<String, String> params = new HashMap<String, String>(3);
		params.put("sex", "男");
		params.put("id", "007");
		params.put("userName", "张三");
		HttpClientUtil.sendFileAndParamsByHttpPost(file, url, params);
	}

4.测试结果

// [2018-07-14 17:08:46] [INFO]  fileName: test, userName: ??, id: 007, sex: ?
		
// [2018-07-14 17:14:31] [INFO]  fileName: test, userName: 张三, id: 007, sex: 男

第一条结果为未设置编码的结果

第二条结果未设置编码后

controller接口注意:

@RequestParam CommonsMultipartFile file, @RequestParam("userName") String username, @RequestParam String id, String sex

若入参名与传递来的参数名一致,则可以不加@RequestParam

若入参名与传递来的参数名不一致,则需要@RequestParam("传过来的参数名")

三.传递json,使用model接收

1.HttpClient类

/**
	 * 通过post请求以json格式发送model
	 * @param t
	 * @param url
	 */
	public static <T> void sendDataJsonByPost(T t, String url) {
		ObjectMapper mapper = new ObjectMapper();
		String data = "";
		try {
			data = mapper.writeValueAsString(t);
		} catch (JsonGenerationException e1) {
			e1.printStackTrace();
		} catch (JsonMappingException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		CloseableHttpClient client = HttpClients.custom().build();
		HttpPost post = new HttpPost(url);
		try {
			// 以entity形式携带参数
			post.setEntity(new StringEntity(data, "UTF-8"));
			// 设置头信息,以josn格式发送
			post.addHeader("Content-Type", "application/json");
			CloseableHttpResponse resp = client.execute(post);
			if (resp.getStatusLine().getStatusCode() == 200) {
				Logger.getLogger(HttpClientUtil.class).info("发送成功");
				Logger.getLogger(HttpClientUtil.class).info(EntityUtils.toString(resp.getEntity()));
			} else {
				Logger.getLogger(HttpClientUtil.class).info("发送失败");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

2.controller

@RequestMapping(params = "sendDataJsonByPost", produces = MediaType.APPLICATION_JSON_VALUE)
	public void sendDataJsonByPost(@RequestBody User user) {
		LoggerFactory.getLogger(getClass()).info(user.toString());
	}

3.测试类

@Test
	public void sendDataJsonByPost() {
		User user = new User("张三", "1"); 
		String url = PropUtil.configProp.getProperty("url") + "/httpClientController.do?sendDataJsonByPost";
		HttpClientUtil.sendDataJsonByPost(user, url);
	}

4.测试结果

[2018-07-14 17:59:48] [INFO]  User [userName=张三, id=1]

四.使用NameValuePair传递参数

1.HttpClient类

/**
	 * 以post方式进行请求,得到布尔类型值
	 * @param url
	 * @param params
	 * @return
	 */
	public static boolean booleanReturnByPost(String url, List<NameValuePair> params) {
		CloseableHttpClient client = HttpClients.custom().build();
		HttpPost post = new HttpPost(url);
		try {
			post.setEntity(new UrlEncodedFormEntity(params));
			CloseableHttpResponse resp = client.execute(post);
			if (resp.getStatusLine().getStatusCode() == 200) {
				// springmvc 返回值不能是布尔类型,所以返回"true" or "false",再进行转换
				// 使用EntityUtils将resp.getEntity()解析
				if (Boolean.parseBoolean(EntityUtils.toString(resp.getEntity()))) {
					return true;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

2.controller

@RequestMapping(params = "booleanReturnByPost")
	public String booleanReturnByPost(String fileName, String userName) {
		LoggerFactory.getLogger(getClass()).info("fileName: {}, userName: {}", fileName, userName);
		if (userName == null) {
			return "true";
		}
		return "false";	
	}

3.测试类

@Test
	public void booleanReturnByPost() {
		Map<String, String> paramsMap = new HashMap<String, String>(2);
		paramsMap.put("fileName", "测试");
		paramsMap.put("username", "张三");
		String url = PropUtil.configProp.getProperty("url") + "/httpClientController.do?booleanReturnByPost";
		System.out.println(HttpClientUtil.booleanReturnByPost(url , paramsMap));
	}

4.测试结果

true

[2018-07-14 18:03:54] [INFO] fileName: 测试, userName: null

userName为null是因为接收参数与发送参数大小写不完全一致

五:关于controller接口的说明会在另外关于springmvc的博客中说明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

future_1024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值