Total Pageviews

2018/04/09

[Spring] Using RestTemplate to do HTTP Post and Get

Problem
How to use Spring RestTemplate to implement HTTP Post and Get.
The requirement is:
1. Using HTTP Get to get JSON string
2. Using HTTP Post to post JSON string to server




How-To

The example is as bellows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    @Autowired
    private RestTemplate restTemplate;
    
    // example for HTTP Get
    String getUrl = "http://192.168.0.1:8080/status";
    try {
       String statusJSONString = restTemplate.getForObject(new URI(getUrl), String.class);
    } catch (RestClientException | URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    
    // example for HTTP Post
    String postUrl = "http://192.168.0.1:8080/train?name=test1";
        
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
  
    HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers);
  
    try {
          restTemplate.postForEntity(new URI(url), entity, String.class);
    } catch (RestClientException | URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }


No comments: