I try to use Spring Restful webservice.
I have created two projects in two eclipse. In one project I have written RestClient program and in another project I have written webservice and stared the webservice over tomcat. I am trying to pass java bean as json communication between client and server.
But I got below exception.
org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
I have tried in many ways but it was unsuccessful. Below is my code snippet.
Client Method :
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();
    }
}
Service Method :
@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;
    }
Track Class :
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 + "]";
    }
}
Also I tried with
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
And
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); 
Finally it is working by made changes as follows :
Added below lines in 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>
Add added jackson-core-2.5.0 & jackson-annotations-2.5.0 jars in classpath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With