问题:使用SpringMVC框架后,接口中入参对象没使用@RequestBody注解,造成postman发起post请求,from-data格式请求可以调通接口,但是raw格式请求调不通接口,然后我加了SpringMVC @ResponseBody 注解,调接口显
示415错误。
SpringMVC添加配置、注解:
1 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
2 <property name="messageConverters">
3 <list>
4 <ref bean="jsonHttpMessageConverter" />
5 </list>
6 </property>
7 </bean>
9 <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
10 <property name="supportedMediaTypes">
11 <list>
12 <value>application/json;charset=UTF-8</value>
13 </list>
14 </property>
15 </bean>
View Code
pom.xml添加jackson包引用:
1 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
2 <dependency>
3 <groupId>com.fasterxml.jackson.core</groupId>
4 <artifactId>jackson-core</artifactId>
5 <version>2.9.6</version>
6 </dependency>
7 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
8 <dependency>
9 <groupId>com.fasterxml.jackson.core</groupId>
10 <artifactId>jackson-databind</artifactId>
11 <version>2.9.6</version>
12 </dependency>
13 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
14 <dependency>
15 <groupId>com.fasterxml.jackson.core</groupId>
16 <artifactId>jackson-annotations</artifactId>
17 <version>2.9.6</version>
18 </dependency>
View Code
Ajax请求时
没有设置Content-Type为application/json。
注释:按照上面配置完成后,可以使用raw调用接口中包含@RequestBody注解的接口,但是此时你会发现form-data这种方式访问接口又调不通了,百度了下,解决如下:
form-data 的 Content-Type 的类型是 application/x-www-form-urlencoded,是表单编码,不同的是还可以提交文件。
raw 的话,有几种,常用的是application/json
如果SpringMVC要接受application/json,需要使用 @RequestBody 注解来接收。
也就是说 @RequestBody 注解接收的是application/json格式的参数(json对象),这种参数使用raw传参可以自定义格式为(JSON(application/json)),但是form-data传参的格式是application/x-www-form-urlencoded的,所以调不通接口。
https://blog.csdn.net/leyangjun/article/details/79221765
https://blog.csdn.net/yixiaoping/article/details/45281721#comments
Content-Type为:application/x-www-form-urlencoded
后端接口正常不处理可以调用,传递的是JSON对象(Ajax中的data),也可以使用@RequestParam注解去获取表单中的值。
Content-Type为:application/json
后端接口入参得用@RequestBody 注解来接收,传递的JSON对象的字符串,传递的不是JSON对象。
<bean id="multipartResolver"
class
="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
此时对以上两种编码格式都支持。
注意:此时需要引入
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
参考:
https://www.dev-heaven.com/posts/34407.html