'In the postman I am getting proper json response but when I hit the service through restTemplate I am getting chinese characters
Code:
RestTemplate template=new RestTemplate();
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity=new HttpEntity<>(body,headers);
ResponseEntity<String> postForEntity = template.postForEntity("url", httpEntity, String.class);
Json Response:
笀∀琀爀愀渀猀愀挀琀椀漀渀䤀䐀∀㨀∀娀㜀㌀㐀䔀㤀㈀㈀㘀㜀㈀㌀㔀㠀㘀㤀㔀∀Ⰰ∀猀琀愀琀甀猀∀㨀 Ⰰ∀爀攀焀吀猀∀㨀∀㈀ ㈀ ⴀ 㐀ⴀ㈀ ∀Ⰰ∀愀搀搀爀倀漀椀渀琀䰀椀猀琀∀㨀嬀笀∀爀攀焀䤀搀∀㨀∀娀㜀㌀㐀䔀㤀㈀㈀㘀㜀㈀㌀㔀㠀㘀㤀㔀∀Ⰰ∀爀攀猀椀䌀漀洀∀㨀∀唀∀Ⰰ∀愀搀搀爀倀渀琀吀欀渀∀㨀∀∀紀崀紀
by using this for loop I am able to get the correct json response:
for(int i=0; i< response.length(); i++) {
encoded += ((char) ((int)response.charAt(i) / 256 ));
}
Postman headers:
Request Headers:
Accept:Application/Json
Content-type:Application/Json
Response Headers:
Content-Type →application/json; charset=utf-8
Date →Thu, 04 Jun 2020 15:41:49 GMT
Server →Server Name
Transfer-Encoding →chunked
But I want to get the response without using this for loop.
Solution 1:[1]
In your code you are trying to receive the response in String format and here is the issue. First receive the response as Object, Once you receive the response as Object then try to convert it in String.
RestTemplate template=new RestTemplate();
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity=new HttpEntity<>(body,headers);
ResponseEntity<Object> postForEntity = template.postForEntity("url", httpEntity, Object.class);
Solution 2:[2]
Maybe you need to pass "Accept-Language" header. It could be possible that postman sends default header value as "en-US"
Solution 3:[3]
The problem is the encoding. when sending your request make sure that you add the header
Content-type:Application/Json; charset=utf-8
And not just
Content-type:Application/Json
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Nandlal |
Solution 3 | Michael Gantman |