使用内容类型为application/x-www-form-urlencoded的Post请求在Spring中无法正常工作。

huangapple go评论95阅读模式
英文:

Post request with content type application/x-www-form-urlencoded not working in Spring

问题

我正在使用OpenAPI生成器生成Spring REST API。以下是代码片段:

  1. openapi: 3.0.2
  2. info:
  3. version: 1.0.0
  4. title: Auth
  5. paths:
  6. '/auth/v1/token':
  7. post:
  8. operationId: getAuthToken
  9. requestBody:
  10. content:
  11. "application/x-www-form-urlencoded":
  12. schema:
  13. $ref: '#/components/schemas/LoginRequest'
  14. responses:
  15. '200':
  16. description: 'Success'
  17. content:
  18. application/json:
  19. schema:
  20. $ref: '#/components/schemas/OnlineAccount'
  21. components:
  22. schemas:
  23. LoginRequest:
  24. type: object
  25. properties:
  26. username:
  27. type: string
  28. password:
  29. type: string
  30. format: password
  31. grant_type:
  32. type: string
  33. required:
  34. - username
  35. - password
  36. - grant_type
  37. OnlineAccount:
  38. title: OnlineAccount
  39. type: object
  40. properties:
  41. id:
  42. type: string

该生成器生成了一个Spring REST API方法(仅为一个有趣的方法):

  1. @ApiOperation(value = "", nickname = "getAuthToken", notes = "", response = OnlineAccount.class, tags={ })
  2. @ApiResponses(value = {
  3. @ApiResponse(code = 200, message = "Success", response = OnlineAccount.class) })
  4. @RequestMapping(value = "/auth/v1/token",
  5. produces = { "application/json" },
  6. consumes = { "application/x-www-form-urlencoded" },
  7. method = RequestMethod.POST)
  8. ResponseEntity<OnlineAccount> getAuthToken(@ApiParam(value = "", required=true) @RequestPart(value="username", required=true) String username,@ApiParam(value = "", required=true) @RequestPart(value="password", required=true) String password,@ApiParam(value = "", required=true) @RequestPart(value="grant_type", required=true) String grantType);

然后我想从集成测试中使用RestTemplate来调用它:

  1. RequestEntity<String> requestEntity =
  2. RequestEntity.post(
  3. new URL("http://localhost:" + applicationPort + "/auth/v1/token").toURI())
  4. .contentType(MediaType.APPLICATION_FORM_URLENCODED)
  5. .body("username%3Dtest%40test-email.com%26password%3Dpassword");
  6. ResponseEntity<OnlineAccount> loginResponse =
  7. restTemplate.exchange(requestEntity, OnlineAccount.class);

然后我遇到了一个错误:

  1. org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded
  2. ...(以下为错误堆栈信息)

我已经在服务器端进行了一些调试,看起来它期望一个多部分内容,但我不明白为什么会出现这种情况。

这是我尝试调用该服务的多个尝试之一。我已经检查了一些使用MultiValueMap的解决方案,还查看了这些问题,但是没有成功:

我的Spring Boot版本:2.3.3-RELEASE(2.3.1-RELEASE也会失败)。

英文:

I'm using OpenAPI generator to generate Spring REST APIs. Here is a fragment:

  1. openapi: 3.0.2
  2. info:
  3. version: 1.0.0
  4. title: Auth
  5. paths:
  6. &#39;/auth/v1/token&#39;:
  7. post:
  8. operationId: getAuthToken
  9. requestBody:
  10. content:
  11. &quot;application/x-www-form-urlencoded&quot;:
  12. schema:
  13. $ref: &#39;#/components/schemas/LoginRequest&#39;
  14. responses:
  15. &#39;200&#39;:
  16. description: &#39;Success&#39;
  17. content:
  18. application/json:
  19. schema:
  20. $ref: &#39;#/components/schemas/OnlineAccount&#39;
  21. components:
  22. schemas:
  23. LoginRequest:
  24. type: object
  25. properties:
  26. username:
  27. type: string
  28. password:
  29. type: string
  30. format: password
  31. grant_type:
  32. type: string
  33. required:
  34. - username
  35. - password
  36. - grant_type
  37. OnlineAccount:
  38. title: OnlineAccount
  39. type: object
  40. properties:
  41. id:
  42. type: string

It generates a Spring REST API method (only an interesting method):

  1. @ApiOperation(value = &quot;&quot;, nickname = &quot;getAuthToken&quot;, notes = &quot;&quot;, response = OnlineAccount.class, tags={ })
  2. @ApiResponses(value = {
  3. @ApiResponse(code = 200, message = &quot;Success&quot;, response = OnlineAccount.class) })
  4. @RequestMapping(value = &quot;/auth/v1/token&quot;,
  5. produces = { &quot;application/json&quot; },
  6. consumes = { &quot;application/x-www-form-urlencoded&quot; },
  7. method = RequestMethod.POST)
  8. ResponseEntity&lt;OnlineAccount&gt; getAuthToken(@ApiParam(value = &quot;&quot;, required=true) @RequestPart(value=&quot;username&quot;, required=true) String username,@ApiParam(value = &quot;&quot;, required=true) @RequestPart(value=&quot;password&quot;, required=true) String password,@ApiParam(value = &quot;&quot;, required=true) @RequestPart(value=&quot;grant_type&quot;, required=true) String grantType);

Then I want to call it from my integration test using RestTemplate:

  1. RequestEntity&lt;String&gt; requestEntity =
  2. RequestEntity.post(
  3. new URL(&quot;http://localhost:&quot; + applicationPort + &quot;/auth/v1/token&quot;).toURI())
  4. .contentType(MediaType.APPLICATION_FORM_URLENCODED)
  5. .body(&quot;username%3Dtest%40test-email.com%26password%3Dpassword&quot;);
  6. ResponseEntity&lt;OnlineAccount&gt; loginResponse =
  7. restTemplate.exchange(requestEntity, OnlineAccount.class);

And I get an error:

  1. org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException: the request doesn&#39;t contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded
  2. at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.init(FileItemIteratorImpl.java:140) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  3. at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.getMultiPartStream(FileItemIteratorImpl.java:194) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  4. at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.findNextItem(FileItemIteratorImpl.java:213) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  5. at org.apache.tomcat.util.http.fileupload.impl.FileItemIteratorImpl.&lt;init&gt;(FileItemIteratorImpl.java:131) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  6. at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:255) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  7. at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:279) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  8. at org.apache.catalina.connector.Request.parseParts(Request.java:2869) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  9. at org.apache.catalina.connector.Request.getParts(Request.java:2771) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  10. at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1098) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  11. at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:95) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  12. at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.&lt;init&gt;(StandardMultipartHttpServletRequest.java:88) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  13. at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.&lt;init&gt;(StandardMultipartHttpServletRequest.java:72) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  14. at org.springframework.web.multipart.support.MultipartResolutionDelegate.asMultipartHttpServletRequest(MultipartResolutionDelegate.java:82) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  15. at org.springframework.web.multipart.support.RequestPartServletServerHttpRequest.&lt;init&gt;(RequestPartServletServerHttpRequest.java:66) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  16. at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:134) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  17. at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  18. at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  19. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  20. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  21. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  22. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  23. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  24. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  25. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  26. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  27. at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  28. at javax.servlet.http.HttpServlet.service(HttpServlet.java:665) ~[javax.servlet-api-4.0.1.jar:4.0.1]
  29. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  30. at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) ~[javax.servlet-api-4.0.1.jar:4.0.1]
  31. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  32. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  33. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.36.jar:9.0.36]
  34. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  35. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  36. at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  37. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  38. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  39. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  40. at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  41. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  42. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  43. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  44. at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93) ~[spring-boot-actuator-2.3.1.RELEASE.jar:2.3.1.RELEASE]
  45. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  46. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  47. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  48. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  49. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
  50. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  51. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  52. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  53. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  54. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  55. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  56. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  57. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  58. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  59. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  60. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  61. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  62. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  63. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  64. at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
  65. at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
  66. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
  67. at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

I've debugged a little the server side and it looks like it expects a multipart content, but I don't understand why.

This is one of several attempts to call the service. I've checked some solutions using MultiValueMap, also these questions, but no success:

Http Post request with content type application/x-www-form-urlencoded not working in Spring

Spring MVC - @RequestParam causing MissingServletRequestParameterException with x-www-form-urlencoded

My Spring boo version: 2.3.3-RELEASE (fails also with 2.3.1-RELEASE)

答案1

得分: 2

你正在使用@RequestPart,该注解期望是MultipartFile类型的内容。如果没有特殊要求,请考虑更改为其他注解。

参考文档:链接

英文:

You are using @RequestPart which expects MultipartFile content type. Change @RequestPart if not specially required.

Read reference

答案2

得分: 2

以下是翻译好的内容:

在 OpenAPI 生成器中存在一个错误(5 天前已打开)
https://github.com/OpenAPITools/openapi-generator/issues/7794

请注意,此问题中引用了一个提交,似乎修复了这个错误。
这是一个单行的 Mustache 模板 formParams.mustache。

如果您依赖于 openapi-generator-maven-plugin,您可以尝试使用 templateDirectory 配置,并将建议的 Mustache 模板放在其中作为修复措施。
这可能对您有帮助。

英文:

there is a bug in open api generator (opened 5 days ago)
https://github.com/OpenAPITools/openapi-generator/issues/7794

Note that there is a commit referenced on this issue which seems to fix the bug.
It's a one-liner mustache template formParams.mustache.

If you rely on openapi-generator-maven-plugin, you could try using the templateDirectory config and put there the mustache template proposed as a fix.
Might do the trick for you.

答案3

得分: 2

刚刚遇到了这个问题。该行为在2020年的4.3.0版本中引入,于2022年得到修复。更多细节请参阅 https://stackoverflow.com/a/71954528/18619318

我发现升级到6.0.0-beta版本后,得到了我所期望的行为。请注意,如果您使用“spring”生成器,辅助类的命名已经发生了变化。

英文:

Just ran into this. The behaviour was introduced in 4.3.0 in 2020, and fixed in 2022. More details in https://stackoverflow.com/a/71954528/18619318

I found that upgrading to 6.0.0-beta gave the behavior I was looking for. Note that naming of helper classes has changed, if you use the "spring" generator.

huangapple
  • 本文由 发表于 2020年9月14日 21:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63885130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定