首次开发基于java spring的API。这些 API 将采用 POST 方式并采用 JSON 作为输入。我不能连接所有点,因为当我从其余客户端调用 api 调用时会出现错误消息。
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>
从 json 序列化的对象
public class PostCountry {
private String country;
public void setCountry(String country){
this.country=country;
}
public String getCountry() {
return country;
}
}
Controller
@RequestMapping(value = "/getCountries", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody String getCountries(PostCountry country) {
System.out.println(country.getCountry());
MapDAOImpl mapDAOImpl = (MapDAOImpl) appContext.getBean("mapDAOImpl");
System.out.println(mapDAOImpl.getCountries(country.getCountry()));
return "";
}
休息客户端抛出错误消息
<u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>
错误
System.out.println(country.getCountry()); is null
最佳答案
问题有 2 倍。我需要在 xml 文件中定义一些 RequestMappingHandlerAdapter。
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
并在模型中定义一个空的构造函数
public class PostCountry {
public String country;
public PostCountry() {}
public PostCountry(String country) {
this.country = country;
}
public void setCountry(String country){
this.country=country;
}
public String getCountry() {
return country;
}
}
@RequestMapping(value = "/getCountries"
, method = RequestMethod.POST
, consumes = "application/json"
, produces = "application/json")
@ResponseBody
@JsonIgnoreProperties(ignoreUnknown = true)
public ReturnCountries getCountries(@RequestBody PostCountry country) {
关于Java Spring POST API json 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30509639/