본문 바로가기
개발/java,spring,springboot

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

by 개발자종혁 2021. 4. 22.
728x90

1.문제 코드

        ObjectMapper objectMapper = new ObjectMapper();
        String url = "http://주소.com";


        // 2. set url of request

        HttpPost post = new HttpPost(url);

        // 3. set body


        if(body != null){

            StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body));
            post.setEntity(entity);

        }


        // set headers as json

        Map<String, String> headers = new HashMap<>();

        // set headers

        headers.forEach((key, value)->{ 

            log.info("header - {}:{}", key, value);

            post.setHeader(key, value);

        });

        try (CloseableHttpClient httpClient = HttpClients.createDefault(); 
             CloseableHttpResponse response = httpClient.execute(post)) {
            int status = response.getStatusLine().getStatusCode();

            String text = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));
            log.info("status:{}, entity:{}", status, text);


        }
        catch (UnsupportedOperationException | IOException e) {
            log.error("error:", e);
            throw e;
        }

2. 코드 수정 & 추가

String entity encoding 수정

StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body));

> 
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body), "UTF-8");

header추가

Map<String, String> headers = new HashMap<>();
headers.put("Content-type", "application/json;charset=UTF-8");
headers.put("Accept", "application/json");
728x90

댓글