6

I want to create a simple webservice that produces text/csv content. But I cannot request it:

@RestController
public class MyServlet {
    @PostMapping(produces = {"text/csv", "application/json"})
    public Object post() {
        //...
    }
}

spring.mvc.contentnegotiation.media-types.csv=text/csv

When I send a post request with Content-Type: text/csv as http header, I'm getting the following error:

415: Content type 'text/csv' not supported

This is my configuration:

@Configuration
public class ContentNegotiationConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
                .favorParameter(true) //favor &format=csv
                .defaultContentType(MediaType.APPLICATION_JSON)
                .parameterName(format);
                //.mediaType("csv", new MediaType("text", "csv")) //also tried without success
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Just to be clear, you want to generate a csv file for your user? – mohammedkhan Aug 14 '18 at 10:37
  • have you tried adding `consumes="text/csv"`?? – miiiii Aug 14 '18 at 10:37
  • Is it consumer instead of producer – mallikarjun Aug 14 '18 at 10:37
  • No, `consumes` is for what data is received from the user. But my user is not sending anything, so consumes is ignored here. I want to generate a csv file. – membersound Aug 14 '18 at 10:38
  • 1
    @mohammedkhan it's not a duplicate. Especially I want the content negotiation to already select the correct response content type, as configured above. The query parameter `&format=csv` should be favored, and as a result a `text/csv` should be generated, as configured in the `application.properties`. – membersound Aug 14 '18 at 10:41
  • @membersound how come [this](https://stackoverflow.com/questions/44778791/how-to-add-csv-mimetype-to-spring-content-negotiation) and answer worked and how it not working in the same configuration(both from you). So are you missing any configuration? – mallikarjun Aug 14 '18 at 10:47
  • do you have `@EnableWebMvc` on `ContentNegotiationConfiguration` class? What version of Spring are you targeting? – diginoise Aug 14 '18 at 10:52
  • `spring-boot-2.0.4.RELEASE`, which automatically adds `@EnableWebMvc`. I can also see during debug, that my `ContentNegotiationConfiguration` is loaded and the configurer actually contains `text/csv` as media type. The question is why it is not matched... – membersound Aug 14 '18 at 10:59

1 Answers1

4

If you (client) expect csv content, client should pass text/csv as Accept header not Content-Type.

reith
  • 2,028
  • 13
  • 26