一.上传文件
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的博客中说明