programing

오류: org.springframework.web.지원되지 않는 HttpMediaType예외:내용 유형 '텍스트/문자열; 문자 집합=UTF-8'은 지원되지 않습니다.

kingscode 2023. 8. 29. 21:33
반응형

오류: org.springframework.web.지원되지 않는 HttpMediaType예외:내용 유형 '텍스트/문자열; 문자 집합=UTF-8'은 지원되지 않습니다.

저는 Spring Data 신입사원입니다.계속 오류가 발생합니다.org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported저는 내부 소비를 바꾸려고 노력했습니다.@RequestMapping에 대한 주석.text/plain하지만 불행히도 도움이 되지 않았습니다.

아이디어 있어요?

감사해요.

내 코드는 다음과 같습니다.

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;

}

}

예외는 다음과 같습니다.

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)

요청은 그렇게 보입니다: 저는 Simple Rest Template Google Extension을 사용하고 있습니다.요청은 다음과 같습니다.

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

의견에 언급된 내용을 바탕으로 가장 간단한 해결책은 다음과 같습니다.

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

솔루션은 당신이 만들고 있는 HTTP 요청이 실제로 가지고 있다고 가정합니다.

Content-Type:application/json대신에text/plain

다음을 통해 게시 요청을 하는 경우Postman그런 다음 이 두 가지 옵션을 선택했는지 확인합니다.

JSON(애플리케이션/json)을 선택해야 합니다.

내용 유형 - 응용 프로그램/json

enter image description here

저는 알고보니 제가 가지고 있었습니다.@JsonManagedReferece없는 하나의 실체로@JsonBackReference다른 참조 엔티티에 있습니다.이것은 마셜러가 실수를 하게 만들었습니다.

효과가 있습니다!포스트맨을 통해 포스트 요청을 하는 경우, 다음 두 가지 옵션을 선택했는지 확인합니다.

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

enter image description here

알겠습니다. 문제의 원인은 직렬화/직렬화였습니다.보내고 받는 객체는 코드가 제출되고 코드와 마스킹된 Phone Number가 반환되는 다음과 같습니다.

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

문제는 생성자에서 마스킹된 모바일 번호에 대해 정의된 Json Property가 없다는 것입니다. 즉, 생성자는

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

제거하여 해결했습니다.@JsonManagedReference그리고 계속@JsonBackReference무한 루프를 피하기 위해.

언급URL : https://stackoverflow.com/questions/24972437/error-org-springframework-web-httpmediatypenotsupportedexception-content-type

반응형