0


spring boot实现postman中form-data传参方式

项目场景:

  1. 开发中遇到对接需求时候,被要求用post请求传form-data数据的时候一脸懵逼,在postman中可以调用,但是程序中怎么调用呢。

问题描述

  1. postman中调用是没问题的
  1. ![](https://img-blog.csdnimg.cn/a08521471b7f401291c030ace716504c.png)

但是在程序中调用就报错了,之前用的是HttpClient的方式请求的

  1. public StringBuffer caller(Map<String,String> map, String strURL) {
  2. // start
  3. HttpClient httpClient = new HttpClient();
  4. HttpConnectionManagerParams managerParams = httpClient
  5. .getHttpConnectionManager().getParams();
  6. // 设置连接超时时间(单位毫秒)
  7. managerParams.setConnectionTimeout(30000);
  8. // 设置读数据超时时间(单位毫秒)
  9. managerParams.setSoTimeout(120000);
  10. PostMethod postMethod = new PostMethod(strURL);
  11. // 将请求参数的值放入postMethod中
  12. String strResponse = null;
  13. StringBuffer buffer = new StringBuffer();
  14. // end
  15. try {
  16. //设置参数到请求对象中
  17. for(String key : map.keySet()){
  18. postMethod.addParameter(key, map.get(key));
  19. }
  20. int statusCode = httpClient.executeMethod(postMethod);
  21. if (statusCode != HttpStatus.SC_OK) {
  22. throw new IllegalStateException("Method failed: "
  23. + postMethod.getStatusLine());
  24. }
  25. BufferedReader reader = null;
  26. reader = new BufferedReader(new InputStreamReader(
  27. postMethod.getResponseBodyAsStream(), "UTF-8"));
  28. while ((strResponse = reader.readLine()) != null) {
  29. buffer.append(strResponse);
  30. }
  31. } catch (Exception ex) {
  32. throw new IllegalStateException(ex.toString());
  33. } finally {
  34. // 释放连接
  35. postMethod.releaseConnection();
  36. }
  37. return buffer;
  38. }

请求普通的接口没问题,但是第三方的接口会报错:415 Unsupported Media Type ,很明显是请求方式的问题,然后我在请求头加上了multipart/form-data,接口请求通了,但是报错参数错误,也就是接口没获取到参数。

  1. postMethod.setRequestHeader("Content-Type", "multipart/form-data");

原因分析:

form-data主要是以键值对的形式来上传参数,同时参数之间以&分隔符分开。我就尝试利用map进行数据的的封装Map<String,String>,结果发现后台无法正确解析参数,是因为map封装后并不是以&链接的。


解决方案:

最后利用spring来作为后端框架,form-data利用LinkedMultiValueMap对象来包装多个参数,参数以key-value形式,中间以&连接。采用restTemplate代码的实现如下:

  1. public String caller(Map<String,String> map, String strURL){
  2. HttpHeaders headers = new HttpHeaders();
  3. MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
  4. headers.add("Content-Type", "multipart/form-data");
  5. //设置参数到请求对象中
  6. for(String key : map.keySet()){
  7. map.add(key, map.get(key));
  8. }
  9. HttpEntity<MultiValueMap<String, Object>> requestParams = new HttpEntity<>(map, headers);
  10. ResponseEntity<String> response = restTemplate.postForEntity(apiUrl,requestParams,String.class);
  11. String result =response.getBody();
  12. return result;
  13. }

最后没用HttpClient 的方式,改为了restTemplate的方式。


本文转载自: https://blog.csdn.net/u011974797/article/details/127554049
版权归原作者 可乐汉堡cola 所有, 如有侵权,请联系我们删除。

“spring boot实现postman中form-data传参方式”的评论:

还没有评论