依赖包信息
<!--CloseableHttpClient\HttpPost依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!--MultipartEntityBuilder依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.10</version>
</dependency>
<!--NameValuePair\BasicNameValuePair\StringEntity依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
一、发送请求
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("xxxxx");//请求地址
... //传入参数
HttpResponse response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
/**获取json格式字符串 **/
String respBody = EntityUtils.toString(resEntity, "UTF-8");
}else{
//返回参数获取异常
}
}else{
//客户端连接异常
}
} catch (Exception e) {
e.printStackTrace();
}
二、参数传递
一、普通参数传参
1. BasicNameValuePair 方式
NameValuePair(简单名称值对节点类型)使用该list来存放参数。
BasicNameValuePair 实现 apache http的NameValuePair接口。
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("参数A", "xxx"));
list.add(new BasicNameValuePair("参数B", "xxx"));
list.add(new BasicNameValuePair("参数C", "xxx"));
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF_8"));
2. 字符串拼接方式
StringBuffer sbr = new StringBuffer();
sbr.append("参数A=xxx&");
sbr.append("参数B=xxx&");
sbr.append("参数C=xxx");
StringEntity stringEntity = new StringEntity(sbr.toString(), "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
二、带有文件参数传参
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
File pdfFile = new File("D:\\A.txt");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
ContentType contentType1 = ContentType.create("multipart/form-data", Consts.UTF_8);
builder.addBinaryBody("binFile", fileInputStream, ContentType.MULTIPART_FORM_DATA, "B.txt");
ContentType contentType = ContentType.APPLICATION_JSON;
LinkedList<FormBodyPart> partsList = new LinkedList<>();
builder.addPart("参数A", new StringBody("xxx",contentType));
builder.addPart("参数A", new StringBody("xxx",contentType));
builder.addPart("参数A", new StringBody("xxx",contentType));
HttpEntity entity = builder.build();
httpPost.setEntity(entity);