Search code examples
javajsonspringhttp-headersx-www-form-urlencoded

How to get and parse JSON response from x-www-form-urlencoded POST, RestTemplate (Java)?


I have this method to make request:

    @Override
    public HttpEntity<MultiValueMap<String, String>> generateRequestEntity(Date date) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("key", "SOME_API_KEY");
        map.add("source", "SOME_API_SOURCE");
        if (date == null)
            map.add("method", "getall");
        else {
            map.add("method", "getfrom");
            map.add("date", new SimpleDateFormat("yyyy-MM-dd").format(date));
        }

        return new HttpEntity<>(map, headers);
    }

I send a request and get a response, as recommended at following link: URL

HttpEntity<MultiValueMap<String, String>> request = generateRequestEntity(date);
ResponseEntity<OnlineSell[]> response = restTemplate.postForEntity(url, request, OnlineSell[].class);
OnlineSell[] onlineSells = response.getBody();

But I have a problem. I am failing when trying to parse JSON-response. OnlineSell - class, that must keep the answer BUT I just can’t create a structure that successfully stores the values ​​of this answer. A very large and complex answer tree comes.

Answer: Can I get JSONObject from it to parse and save manually? Or can I get help with JSON parsing by previously updating this post and adding it (answer form Postman)?


Solution

  • What you can do is to consider the ResponseEntity as a String. Then afterwards you can use objectMapper with readValue(),

    Something like this:

    ResponseEntity<String> response = restTemplate().postForEntity(url, request, String.class);
    
    String body = response.getBody();
    OnlineSell[] onlineSells = new ObjectMapper().readValue(body, OnlineSell[].class);