BAEL-6647: How to handle character encoding in JSON POST Request (#14335)

Co-authored-by: Tapan Avasthi <tavasthi@Tapans-MacBook-Air.local>
This commit is contained in:
Tapan Avasthi 2023-07-02 21:17:44 +05:30 committed by GitHub
parent ec8f9b4006
commit b119316bf4
2 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package com.baeldung.resttemplate;
import java.util.Collections;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(RestTemplateApplication.class);
app.setDefaultProperties(Collections.singletonMap("server.servlet.encoding.charset", "ISO-8859-1"));
app.run(args);
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.resttemplate.postjson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import org.json.JSONException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.RestTemplateApplication;
import com.baeldung.resttemplate.web.dto.Person;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateApplication.class)
public class RestTemplatePostRequestEncodingLiveTest {
private static String createPersonUrl;
private static RestTemplate restTemplate;
@BeforeClass
public static void runBeforeAllTestMethods() throws JSONException {
createPersonUrl = "http://localhost:8080/spring-rest/createPerson";
restTemplate = new RestTemplate();
}
@Test
public void givenJapaneseNameInDataWithoutHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveIncorrectly() {
Person japanese = new Person(100, "関連当");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(person);
assertNotEquals("関連当", person.getName());
}
@Test
public void givenJapaneseNameInDataWithHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveCorrectly() {
Person japanese = new Person(100, "関連当");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-type", "application/json;charset=UTF-8");
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(person);
assertEquals("関連当", person.getName());
}
}