Search code examples
resttemplate

how to use restTemplate send a jsonArray?


i need send a jsonArray use restTemplate, but i don't know the right way.here is my code. can somebody tell me where is the problem?

the requestHandler:

@CrossOrigin
    @RequestMapping(path = "/duplication", method = RequestMethod.GET)
    public ResponseEntity<Boolean> checkDeviceDuplication(
            @RequestHeader("token") String token,
            @RequestBody Set<DeviceCheckDuplicationMessage> devicesToCheck
            )
    {
        System.out.println("size:" + devicesToCheck.size());
    }

the restTemplate client:

String authorityValidUrl = "http://192.168.227.100:15004/duplication";
                RestTemplate restTemplate = restTemplateBuilder.build();
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.set("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkaXNwbGF5TmFtZSI6IuWuieaWh-mRqyIsInJvbGVzIjpbIlJPTEVfQ0hFQ0tBTkRGSVhNQU5BR0VSIiwiUk9MRV9QTEFORU1BTkFHRVIiLCJST0xFX1BST0pFQ1RNQU5BR0VSIiwiUk9MRV9URUNIU1RBVFVTTUFOQUdFUiIsIlJPTEVfQ0FUQUxPR1VFTUFOQUdFUiIsIlJPTEVfVFJJUE1BTkFHRVIiLCJST0xFX1VTRVIiXSwiZXhwIjoxNTQ1Mzk2MDc0LCJ1c2VybmFtZSI6ImFud3gifQ.tM2t7yLcg9fHr78KtCf0ocscy6nOAZioJ0V_zGERKaM");
                requestHeaders.setContentType(MediaType.APPLICATION_JSON);

                Set<DeviceCheckDuplicationMessage> devicesToCheck = new HashSet<>();
                devicesToCheck.add(new DeviceCheckDuplicationMessage("cn", "en", "model", "sn"));
                devicesToCheck.add(new DeviceCheckDuplicationMessage("name_cn1", "name_en1", "model1", "sn1"));

                String body = JSON.toJSONString(devicesToCheck);

                HttpEntity<String> requestEntity = new HttpEntity<>(body, requestHeaders);
                requestEntity.getBody();
                ResponseEntity<Boolean> validResult = restTemplate.exchange(
                        new URI(authorityValidUrl), 
                        HttpMethod.GET, 
                        requestEntity, 
                        Boolean.class
                    );

now requestHandler show me missing requestBody.

but i use postman for request with same header and jsonData is OK.


Solution

  • i try change http method to post and requestbody to an object. and it works.

    according to the doc https://docs.spring.io/spring/docs/5.1.3.RELEASE/spring-framework-reference/integration.html#spring-integration

    You need not explicitly set the Content-Type header of the request. In most cases, you can find a compatible message converter based on the source Object type, and the chosen message converter sets the content type accordingly. If necessary, you can use the exchange methods to explicitly provide the Content-Type request header, and that, in turn, influences what message converter is selected.

    and

    Objects passed into and returned from RestTemplate methods are converted to and from raw content with the help of an HttpMessageConverter.

    On a POST, an input object is serialized to the request body

    On a GET, the body of the response is deserialized to an output Object

    so i change my code to this and it works.

    @Test
        public void testValid() {
            try {
                    String authorityValidUrl = "http://192.168.227.100:15004/duplication";
                    HttpHeaders requestHeaders = new HttpHeaders();
                    requestHeaders.set("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkaXNwbGF5TmFtZSI6IuWuieaWh-mRqyIsInJvbGVzIjpbIlJPTEVfQ0hFQ0tBTkRGSVhNQU5BR0VSIiwiUk9MRV9QTEFORU1BTkFHRVIiLCJST0xFX1BST0pFQ1RNQU5BR0VSIiwiUk9MRV9URUNIU1RBVFVTTUFOQUdFUiIsIlJPTEVfQ0FUQUxPR1VFTUFOQUdFUiIsIlJPTEVfVFJJUE1BTkFHRVIiLCJST0xFX1VTRVIiXSwiZXhwIjoxNTQ1NzE2NzQ1LCJ1c2VybmFtZSI6ImFud3gifQ.two6KeWnV2egnEk4QC3PuIPJfiRSSReNtKfzbE9qSQQ");
                    //requestHeaders.setContentType(MediaType.APPLICATION_JSON);
                    
                    Set<DeviceCheckDuplicationMessage> devicesToCheck = new HashSet<>();
                    devicesToCheck.add(new DeviceCheckDuplicationMessage("cn", "en", "model", "sn"));
                    devicesToCheck.add(new DeviceCheckDuplicationMessage("name_cn1", "name_en1", "model1", "sn1"));
                    
                    HttpEntity<Set<DeviceCheckDuplicationMessage>> requestEntity = new HttpEntity<>(devicesToCheck, requestHeaders);
                    ResponseEntity<Boolean> validResult = restTemplate.exchange(
                            new URI(authorityValidUrl), 
                            HttpMethod.POST, //HttpMethod.GET,
                            requestEntity, 
                            Boolean.class
                        );
                    boolean result = Boolean.valueOf(validResult.getBody());
                    System.out.println(result);
                    System.out.println(validResult.getStatusCodeValue());
            }catch(Exception e) {
                e.printStackTrace();
            }
        }