springboot实现postman中form-data传参实现过程
项目场景
开发中遇到对接需求时候,被要求用post请求传form-data数据的时候一脸懵逼,在postman中可以调用,但是程序中怎么调用呢。
问题描述
在postman中调用是没问题的

但是在程序中调用就报错了,之前用的是HttpClient的方式请求的
public StringBuffer caller(Map<String,String> map, String strURL) {
// start
HttpClient httpClient = new HttpClient();
HttpConnectionManagerParams managerParams = httpClient
.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(30000);
// 设置读数据超时时间(单位毫秒)
managerParams.setSoTimeout(120000);
PostMethod postMethod = new PostMethod(strURL);
// 将请求参数的值放入postMethod中
String strResponse = null;
StringBuffer buffer = new StringBuffer();
// end
try {
//设置参数到请求对象中
for(String key : map.keySet()){
postMethod.addParameter(key, map.get(key));
}
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new IllegalStateException("Method failed: "
+ postMethod.getStatusLine());
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(
postMethod.getResponseBodyAsStream(), "UTF-8"));
while ((strResponse = reader.readLine()) != null) {
buffer.append(strResponse);
}
} catch (Exception ex) {
throw new IllegalStateException(ex.toString());
} finally {
// 释放连接
postMethod.releaseConnection();
}
return buffer;
}请求普通的接口没问题,但是第三方的接口会报错:415 Unsupported Media Type ,很明显是请求方式的问题,然后我在请求头加上了multipart/form-data,接口请求通了,但是报错参数错误,也就是接口没获取到参数。
postMethod.setRequestHeader("Content-Type", "multipart/form-data");原因分析
form-data主要是以键值对的形式来上传参数,同时参数之间以&分隔符分开。
我就尝试利用map进行数据的的封装Map<String,String>,结果发现后台无法正确解析参数,是因为map封装后并不是以&链接的。
解决方案
最后利用spring来作为后端框架,form-data利用LinkedMultiValueMap对象来包装多个参数,参数以key-value形式,中间以&连接。
采用restTemplate代码的实现如下:
public String caller(Map<String,String> map, String strURL){
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
headers.add("Content-Type", "multipart/form-data");
//设置参数到请求对象中
for(String key : map.keySet()){
map.add(key, map.get(key));
}
HttpEntity<MultiValueMap<String, Object>> requestParams = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(apiUrl,requestParams,String.class);
String result =response.getBody();
return result;
}最后没用HttpClient 的方式,改为了restTemplate的方式。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
解决spring-boot-maven-plugin报红的问题
这篇文章主要给大家介绍一下如何解决spring-boot-maven-plugin报红的问题,文中通过图文讲解的非常详细,具有一定的参考价值,需要的朋友可以参考下2023-08-08
mybatis-plus 查询传入参数Map,返回List<Map>方式
这篇文章主要介绍了mybatis-plus 查询传入参数Map,返回List<Map>方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12
java面试常见问题---ConcurrentHashMap
ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成。Segment的结构和HashMap类似,是一种数组和链表结构,今天给大家普及java面试常见问题---ConcurrentHashMap知识,一起看看吧2021-06-06
springmvc利用jquery.form插件异步上传文件示例
本篇文章主要介绍了springmvc利用jquery.form插件异步上传文件示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2017-01-01
Spring Boot常用注解速查表(30个必会注解+实战案例)
这篇文章主要介绍了Spring Boot常用注解速查表(30个必会注解+实战案例),本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2026-03-03


最新评论