java中如何使用form data格式的参数调用接口呢?
									
下文笔者讲述java代码中使用form data格式的参数调用接口的方法分享,如下所示
				 
				form data格式调用接口
实现思路:
    1.使用EntityBuilder组装数据
    2.使用httppost.setEntity(EntityBuilder.build())
       发送数据即可
例:
 
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("数据推送失败");
}
									
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

			
               
               
               
               
          
