I am new to Spring and I need my Java app to connect to another API over HTTP (JSON, RESTful). Does the Spring Framework have anything like a JSON HTTP Rest Client? What do Spring developers usually use?
Spring RestTemplate Configuration HttpComponentsClientHttpRequestFactory is ClientHttpRequestFactory implementation that uses Apache HttpComponents HttpClient to create requests.
RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interface uses Apache's HttpClient.
Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated. It will probably stay for some more time but will not have major new features added going forward in future releases. So it's not advised to use RestTemplate in new code.
I achieved what I needed with the following:
import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestClient { private String server = "http://localhost:3000"; private RestTemplate rest; private HttpHeaders headers; private HttpStatus status; public RestClient() { this.rest = new RestTemplate(); this.headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); headers.add("Accept", "*/*"); } public String get(String uri) { HttpEntity<String> requestEntity = new HttpEntity<String>("", headers); ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.GET, requestEntity, String.class); this.setStatus(responseEntity.getStatusCode()); return responseEntity.getBody(); } public String post(String uri, String json) { HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers); ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.POST, requestEntity, String.class); this.setStatus(responseEntity.getStatusCode()); return responseEntity.getBody(); } public void put(String uri, String json) { HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers); ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.PUT, requestEntity, null); this.setStatus(responseEntity.getStatusCode()); } public void delete(String uri) { HttpEntity<String> requestEntity = new HttpEntity<String>("", headers); ResponseEntity<String> responseEntity = rest.exchange(server + uri, HttpMethod.DELETE, requestEntity, null); this.setStatus(responseEntity.getStatusCode()); } public HttpStatus getStatus() { return status; } public void setStatus(HttpStatus status) { this.status = status; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With