Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
Asked Answered
M

10

60

I'm newbie in Spring Data. I keep getting the error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported I've tried to change consumes inside @RequestMapping annotation to text/plain but unfortunately it didn't help.*

Any ideas?

Thanks,

My Code looks like this:

package com.budget.processing.application;


import com.budget.business.service.Budget;
import com.budget.business.service.BudgetItem;
import com.budget.business.service.BudgetService;
import com.budget.processing.dto.BudgetDTO;
import com.budget.processing.dto.BudgetPerConsumerDTO;
import com.utils.Constants;
import com.common.utils.config.exception.GeneralException;
import org.apache.log4j.Logger;
import org.joda.time.YearMonth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.MediaType;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Controller("budgetManager")
@RequestMapping(value = "budget", produces  = Constants.RESPONSE_APP_JSON)
@Transactional(propagation = Propagation.REQUIRED)
public class BudgetManager {

private static final Logger logger = Logger.getLogger(BudgetManager.class);


@Autowired
private BudgetService budgetService;


@RequestMapping(method = RequestMethod.GET)
public
@ResponseBody
Collection<BudgetDTO> getBudgetMonthlyAllConsumers() throws GeneralException {

    List<Budget> budgetList = budgetService.getBudgetForAllConsumers();
    List<BudgetDTO> bugetDtos = new ArrayList<>();
    for (Budget budget : budgetList) {
        BudgetDTO budgetDTO = generateBudgetDto(budget);
        bugetDtos.add(budgetDTO);
    }
    return bugetDtos;
}


@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON)
public
@ResponseBody
Collection<BudgetDTO> updateConsumerBudget(@RequestParam(value = "budgetPerDate", required = false)

                          ArrayList<BudgetPerConsumerDTO> budgetPerDate) throws GeneralException, ParseException {

    List<BudgetItem> budgetItemList = new ArrayList<>();
    List<Budget> budgets = new ArrayList<>();
    if (budgetPerDate != null) {
        for (BudgetPerConsumerDTO budgetPerConsumerDTO : budgetPerDate) {
            budgetItemList.add(budgetService.createBudgetItemForConsumer(budgetPerConsumerDTO.getId(), new YearMonth(budgetPerConsumerDTO.getDate()), budgetPerConsumerDTO.getBudget()));
        }
    }

    budgets = budgetService.getBudgetForAllConsumers();
    List<BudgetDTO> budgetDTOList = new ArrayList<>();
    for (Budget budget : budgets) {
        BudgetDTO budgetDto = generateBudgetDto(budget);
        budgetDTOList.add(budgetDto);
    }
    return budgetDTOList;

}

}

Here is the exception I get:

ERROR 2014-07-26 18:05:10.737 (GlobalExceptionHandler.eITFMSException: 86) Error executing Web Service org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:215)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:289)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:229)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:56)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:298)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1091)

The request looks like that: i'm using Simple Rest Template Google Extension. the Request looks like the following:

localhost:8080/rest
1 requests ❘ 140 B transferred
HeadersPreviewResponseCookiesTiming
Remote Address:localhost:8080
Request URL: localhost:8080/rest/budget
Request Method:PUT
Status Code:500 Internal Server Error
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,he;q=0.6
Connection:keep-alive
Content-Length:331
Content-Type:text/plain;charset=UTF-8
Cookie:JSESSIONID=AE87EEB7A73B9F9E81956231C1735814
Host:10.23.204.204:8080
Origin:chrome-extension://fhjcajmcbmldlhcimfajhfbgofnpcjmb
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Request Payloadview parsed
{
"budgetPerDate":
[

         {
            "id":942,
            "date":[
               2014,
               1,
               1
            ],
    "budget": 100
         },
         {
            "id":942,
            "date":[
               2014,
               2,
               1
            ],
    "budget": 150
         }
 ]
}
Merous answered 26/7, 2014 at 15:12 Comment(14)
Please give more of the stacktrace - at least enough to know in what class and method the exception occurs ...Schematize
I added some ot the stacktrace. let me know if there is a need for moreMerous
Show us what you send in your request, headers and body.Pleasure
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)Acquittal
@SotiriosDelimanolis i've added the request. hope it's clear enoughMerous
@ankur-singhal in which spring version are you using? i don't have MediaType.APPLICATION_JSON_VALUE . i'm using: Spring 3.2.2Merous
You're using the wrong MediaType class, WS vs Spring's, but that shouldn't matter.Pleasure
From what I cat tell from the log of the HTTP request you posted, you are using Content-Type:text/plain. Am I right?Massotherapy
Yeah, that doesn't make sense. You are sending JSON.Pleasure
@geonal yeah i've notice that too, i'm using a different tool now for my Rest request (IntelliJ plugin ) and i don't get the following exception but the parameter: budgetPerDate is sending as null for some reasonMerous
@SotiriosDelimanolis - I know, i switched to a different Rest plugin, sending the right Content-Type:application/json, and the parameter: budgetPerDate is passing as nullMerous
So what you actually want is to have your controller method use the JSON that is posted in the body?Massotherapy
@geonal, yes inside the request bodyMerous
Content-type is wrong. It should mention that its JSON text.Plagio
M
42

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Massotherapy answered 26/7, 2014 at 17:51 Comment(4)
It won't work if we can't change Content-Type for clients. how to support the Content type 'text/plain;charset=UTF-8' in Spring. Any help in that.Benghazi
@Benghazi it worked for me without any consumes annotation. Simply changed Postman content-type to 'JSON' instead of 'Text'Forewent
@Forewent that is changing it on the 'client' side. jeevs is asking how to change it on the spring side assuing the clients are using the type "text/plain;charset=UTF-8"Markle
@Benghazi I had the same response error when submitting the request in Postman. Changed content-type to 'JSON' instead of 'Text'. It worked.Nominal
T
32

Incase if you are giving a post request through Postman then make sure you have chosen these 2 options

1. JSON (application/json) should be chosen enter image description here

2. Content-Type - application/json

enter image description here

Tamboura answered 19/7, 2021 at 18:22 Comment(0)
G
20

For me it turned out that I had a @JsonManagedReferece in one entity without a @JsonBackReference in the other referenced entity. This caused the marshaller to throw an error.

Geanine answered 8/11, 2015 at 19:53 Comment(1)
Had the same issue today, and it was pretty hard to figure out. Basically I just stepped my way through the debugger to find it. Even with log level set to trace the exception is just not logged. Very awkward exception handling at this part of Spring. Deserialization errors should never end up in a 415 status, rather a 400 or even 500...Buttermilk
I
1

It works! Incase if you are giving a post request through Postman then make sure you have chosen these 2 options

https://arabicprogrammer.com/article/74621056167/

enter image description here

Intestate answered 13/10, 2022 at 23:10 Comment(0)
L
1

You could try to change the value of the Content-Type header in your request from Content-Type: text/plain to Content-Type: application/json.

In case you are using Postman for the POST request then make sure you have chosen this option (which will change the header value):

https://i.sstatic.net/BsWGH.png

Lynea answered 2/8, 2023 at 20:26 Comment(0)
H
0

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}
Hisakohisbe answered 20/4, 2017 at 21:2 Comment(0)
S
0

I solved by removed @JsonManagedReference and keep @JsonBackReference as it to avoid infinity loop .

Shostakovich answered 13/4, 2021 at 10:15 Comment(0)
S
0

For anyone calling their Spring Backend from a ReactJS/Javascript frontend , you can add header.append('Content-Type', 'application/json'); on your header. Basically, you do this:

const header = new Headers();
header.append('Content-Type', 'application/JSON);
Soliloquy answered 6/10, 2023 at 21:45 Comment(0)
L
0

When using @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON)...

on consumes instead of MediaType.APPLICATION_JSON use MediaType.APPLICATION_JSON_VALUE

Linguistician answered 3/1 at 21:4 Comment(0)
G
0

By default, MappingJackson2HttpMessageConverter supports application/json and application/*+json with UTF-8 character set. This can be overridden by setting the supportedMediaTypes property. I add my converter and it works for me:

@Component
class MappingJackson2HttpMessageConverterWithTextPlainSupport(objectMapper: ObjectMapper) :
    MappingJackson2HttpMessageConverter(objectMapper) {
    init {
        supportedMediaTypes = supportedMediaTypes + MediaType.TEXT_PLAIN
    }
}
Grampositive answered 13/2 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.