ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • RestTemplate 한글 문제
    개발 2015. 1. 13. 19:02
    반응형

    Spring에서 http 기반의 메시지 처리는 HttpMessageConverter를 이용한다.


    RestTemplate 클래스의 postxxx 메서드를 이용해서 파라미터를 전송하면 FormHttpMessageConverter를 사용하게됨.

    FormHttpMessageConverter는 넘겨주는 파라미터 타입에 따라서 HttpMessageConverter 종류를 다르게 사용함.


    한글 깨지는 문제는 StringHttpMessageConverter의 기본 캐릭터셋이 UTF-8 아님.


    해결책은 아래 설정 참조.


    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">

    <property name="messageConverters">

    <list>

    <bean class="org.springframework.http.converter.FormHttpMessageConverter">

    <property name="partConverters">

    <list>

    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">

    </bean>

    <bean class="org.springframework.http.converter.StringHttpMessageConverter">

    <constructor-arg>

    <bean class="java.nio.charset.Charset" factory-method="forName">

    <constructor-arg value="UTF-8" />

    </bean>

    </constructor-arg>

    <property name="writeAcceptCharset" value="false" />

    </bean>

    <bean class="org.springframework.http.converter.ResourceHttpMessageConverter">

    </bean>

    </list>

    </property>

    </bean>

    <bean class="org.springframework.http.converter.StringHttpMessageConverter">

    <constructor-arg>

    <bean class="java.nio.charset.Charset" factory-method="forName">

    <constructor-arg value="UTF-8" />

    </bean>

    </constructor-arg>

    </bean>

    </list>

    </property>

    </bean> 




    아래부부은 <constructor-arg value="UTF-8" /> 이렇게 변경해도됨

    <constructor-arg>

    <bean class="java.nio.charset.Charset" factory-method="forName">

    <constructor-arg value="UTF-8" />

    </bean>

    </constructor-arg> 


    Java Code

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();

    formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));

    List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();

    partConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

    partConverters.add(new ResourceHttpMessageConverter());

    partConverters.add(new ByteArrayHttpMessageConverter());

    formHttpMessageConverter.setPartConverters(partConverters);

    messageConverters.add(formHttpMessageConverter);

    messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

    RestTemplate restTemplate = new RestTemplate(messageConverters);


    반응형
Designed by Tistory.