我正在尝试使用Spring Restful webservice。
我在两次日食中创建了两个项目。在一个项目中,我编写了RestClient程序,在另一个项目中,我编写了webservice,并在tomcat上查看了web服务。我试图将java bean作为客户端和服务器之间的json通信传递。
但是我得到了以下异常。
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
我在很多方面尝试过,但没有成功。以下是我的代码段。
客户端方法:
private static void postTrack() {
try {
final String uri = "http://localhost:8181/RestWS/test";
Track track = new Track();
track.setTitle("Singer");
track.setSinger("Shas");
RestTemplate restTemplate = new RestTemplate();
Track responseTrack = restTemplate.postForObject(uri, track, Track.class);
} catch (Exception e) {
e.printStackTrace();
}
}
服务方式:
@RequestMapping(value = "/test", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody Track testMethod(@RequestBody Track track) {
System.out.println(" Inside Test Method : ");
System.out.println(" In GreetingController.greeting() "+track.getSinger());
return track;
}
跟踪课程:
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
@Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
我也试过
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
并且
MultiValueMap<String, String> header = new LinkedMultiValueMap<String, String>();
header.add("Content-Type", "application/json");
HttpEntity<Object> httpEntity = new HttpEntity<Object>(track, header);
ResponseEntity<Track> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, Track.class);
答案 0 :(得分:2)
最后它的工作方式如下:
在servlet xml中添加了以下行。
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
添加添加的jackson-core-2.5.0&amp; jackson-annotations-2.5.0罐子在类路径中。