本文已参与[新人创作礼]活动,一起开启掘金创作之路。
前言
调用第三方提供的接口,接口参数要求是form data。
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
1.基本使用
CloseableHttpClient httpclient = HttpClients.createDefault();
//post 请求
HttpPost httppost =new HttpPost(请求的地址);
//创建 MultipartEntityBuilder,以此来构建我们的参数
MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
//设置字符编码,防止乱码
ContentType contentType=ContentType.create("text/plain", Charset.forName("UTF-8"));
//业务类型 这里int类型也是用引号包着传过去
EntityBuilder.addPart("name",new StringBody("传的数据",contentType));
//文件类型
EntityBuilder.addBinaryBody("fileList",new File("文件的地址"));
2.如果是数组
EntityBuilder.addPart("name",new StringBody("传的数据1",contentType));
EntityBuilder.addPart("name",new StringBody("传的数据2",contentType));
3.如果是list
accountlist.get[0].setAmountCollected("传的数据");
EntityBuilder.addPart("accountlist["+one+"].amountCollected",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+one+"].bankAbbrevation",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+two+"].amountCollected",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+two+"].bankAbbrevation",new StringBody("传的数据",contentType));
4.参数组装,发送数据
//参数组装
httppost.setEntity(EntityBuilder.build());
log.error("httppost的数据:" + httppost);
//发送全球请求
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity(); //获取响应的对象内容
String returnStr = EntityUtils.toString(entity, Consts.UTF_8);//进行相应内容文本展示并编码
log.error("返回数据:" + returnStr);
if (StringUtils.isEmpty(returnStr)) {
throw new BusinessException("数据推送失败");
}
accountlist.get[0].setAmountCollected("传的数据");
EntityBuilder.addPart("accountlist["+one+"].amountCollected",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+one+"].bankAbbrevation",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+two+"].amountCollected",new StringBody("传的数据",contentType));
EntityBuilder.addPart("accountlist["+two+"].bankAbbrevation",new StringBody("传的数据",contentType));
//参数组装
httppost.setEntity(EntityBuilder.build());
log.error("httppost的数据:" + httppost);
//发送全球请求
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity(); //获取响应的对象内容
String returnStr = EntityUtils.toString(entity, Consts.UTF_8);//进行相应内容文本展示并编码
log.error("返回数据:" + returnStr);
if (StringUtils.isEmpty(returnStr)) {
throw new BusinessException("数据推送失败");
}