bogdanalex
bogdanalex

Reputation: 73

POST using RestTemplate, query parameters and request body

I am trying to learn RestTemplate and for that made two test spring-boot applications, client and server. Tried some examples on google before asking here, and sorry for the duplicate post if I missed it.

@Slf4j
@RestController
public class ServerController {

@PostMapping("/post")
@ResponseBody
public Resource post(@RequestBody Map<String, String> body,
                     @RequestParam(name = "path", defaultValue = "NAN") String path) {

    if (!body.get("key").equalsIgnoreCase("valid")){
        return Resource.builder().ip("'0.0.0.0").scope("KEY NOT VALID").serial(0).build();
    }

    switch (path) {
        case "work":
            return Resource.builder().ip("115.212.11.22").scope("home").serial(123).build();
        case "home":
            return Resource.builder().ip("115.212.11.22").scope("home").serial(456).build();
        default:
            return Resource.builder().ip("127.0.01").scope("local").serial(789).build();
    }
}

}

And here is my ClientController

@Slf4j
@RestController
public class ClientController {

@GetMapping("/get")
public Resource get() {
    String url = "http://localhost:8085/post";
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
    httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
    body.add("key", "valid");
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, httpHeaders);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Resource> response = restTemplate.exchange(url, HttpMethod.POST, entity, Resource.class, Collections.singletonMap("path", "home"));
    return response.getBody();
}

}

In ClientController I am trying to mimic what I did in Postman but without luck.

Postman PrintScreen

What am I doing wrong? Thank you!

Upvotes: 3

Views: 8673

Answers (1)

bogdanalex
bogdanalex

Reputation: 73

Managed to figure it out. Had to refactor like this

@GetMapping("/get")
public Resource get(){
    String url = "http://localhost:8085/post";

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("path", "home");

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(Collections.singletonMap("key", "valid"), httpHeaders);

    Resource resource = restTemplate.postForObject(builder.toUriString(), request, Resource.class);

    return resource;
}

Upvotes: 3

Related Questions