[java] Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

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
         }
 ]
}

This question is related to java spring spring-mvc

The answer is


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


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;
}

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)