user3232446
user3232446

Reputation: 439

Spring Rest Controller return 406 NOT acceptable for text/plain

I have a problem with rest controller and text/plain. I have read many answers here and tried lot of Solutions without success. I have a rest controller that should return a String as text/plain. Here is my Controller:

@RestController
@RequestMapping(value = "/content", headers="Accept=*/*",  
produces={"text/plain", "application/json"})
public class MyController {

@GetMapping(value = "", produces = {MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<String> getContent() {
    return ResponseEntity.ok("a,b,c\n1,2,3\n3,4,5");
}

so when i make a call like this:

https://localhost:9002/rest/v2/content -H "accept: text/plain"

I get 406 Not Acceptable Response with message: Could not find acceptable representation

But with:

https://localhost:9002/rest/v2/content -H "accept: application/json"

i got the excepted result with:

content-type: text/plain

in the Response Header.

I tried to adjust the ContenNegociationManager in my WebMvcConfigurationSupport like this:

@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer)
{
    configurer.favorPathExtension(false).
            favorParameter(false).
            parameterName("mediaType").
            ignoreAcceptHeader(false).
            useJaf(false).
            defaultContentType(MediaType.APPLICATION_JSON).
            mediaType("properties", MediaType.TEXT_PLAIN);
}

I also tried with:

mediaType("plain", MediaType.TEXT_PLAIN);

and I still get the same Response 406.

My Converter List is defined as:

<util:list id="myConverters">
    <ref bean="customJsonHttpMessageConverter"/>
    <ref bean="customXmlHttpMessageConverter"/>
</util:list>

<bean id="customJsonHttpMessageConverter" parent="jsonHttpMessageConverter">
    <property name="jaxbContextFactory" ref="customJaxbContextFactory" />
</bean>
    
<bean id="customXmlHttpMessageConverter" parent="xmlHttpMessageConverter">
    <property name="jaxbContextFactory" ref="customJaxbContextFactory" />
</bean>

and in the Configuration:

@Override
protected void configureMessageConverters(final List<HttpMessageConverter<?>> converters)
{
    converters.addAll(myConverters);
}

What am I missing here?

Upvotes: 2

Views: 1479

Answers (1)

user3232446
user3232446

Reputation: 439

Thank you @CodeScale for the hint. I fixed it by adding the StringHttpMessageConverter to my Converters.

@Override
protected void configureMessageConverters(final List<HttpMessageConverter<?>> converters)
{
    myConverters.add(new StringHttpMessageConverter());
    converters.addAll(myConverters);
}

Upvotes: 1

Related Questions