Skip to content

Commit

Permalink
Use UTF-8 for application/json in MockHttpServletResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
izeye committed Dec 23, 2021
1 parent 544e9bb commit bd31fcf
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
Expand Down Expand Up @@ -315,6 +316,11 @@ public void setContentType(@Nullable String contentType) {
if (mediaType.getCharset() != null) {
setExplicitCharacterEncoding(mediaType.getCharset().name());
}
else {
if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
this.characterEncoding = StandardCharsets.UTF_8.name();
}
}
}
catch (Exception ex) {
// Try to get charset value anyway
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import org.springframework.http.MediaType;
import org.springframework.web.util.WebUtils;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -360,6 +361,14 @@ void servletWriterAutoFlushedForString() throws IOException {
assertThat(response.getContentAsString()).isEqualTo("X");
}

@Test
void getContentAsStringWhenContentTypeIsApplicationJsonShouldUseUtf8() throws IOException {
String content = "{\"value\": \"테스트\"}";
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(content);
assertThat(response.getContentAsString()).isEqualTo(content);
}

@Test
void sendRedirect() throws IOException {
String redirectUrl = "/redirect";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
Expand Down Expand Up @@ -315,6 +316,11 @@ public void setContentType(@Nullable String contentType) {
if (mediaType.getCharset() != null) {
setExplicitCharacterEncoding(mediaType.getCharset().name());
}
else {
if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
this.characterEncoding = StandardCharsets.UTF_8.name();
}
}
}
catch (Exception ex) {
// Try to get charset value anyway
Expand Down

0 comments on commit bd31fcf

Please sign in to comment.