package client; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import server.Word; public class MyClient { private static final RestTemplate restTemplate = new RestTemplate(); private static final String serverAddress = "http://localhost:1337"; public static void main(String[] args) { // POST String postPath = "/dictionary/add"; Word word = new Word("computer", "an electronic machine that can store and arrange large amounts of information"); ResponseEntity postResponse = postRequest(serverAddress + postPath, word); System.out.println(postResponse); // GET #1 String getPath = "/dictionary/get/computer"; ResponseEntity getResponse = getRequest(serverAddress + getPath); System.out.println(getResponse); System.out.println(getResponse.getBody()); // PUT String putPath = "/dictionary/modify"; word = new Word("computer", "little box with many wires and a huge number of bright lights"); ResponseEntity putResponse = putRequest(serverAddress + putPath, word); System.out.println(putResponse); // GET #2 getResponse = getRequest(serverAddress + getPath); System.out.println(getResponse); System.out.println(getResponse.getBody()); // DELETE String deletePath = "/dictionary/delete/computer"; ResponseEntity deleteResponse = deleteRequest(serverAddress + deletePath); System.out.println(deleteResponse); // GET #3 getResponse = getRequest(serverAddress + getPath); System.out.println(getResponse); System.out.println(getResponse.getBody()); } public static ResponseEntity postRequest(String url, Word word) { try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity<>(word, headers); return restTemplate.postForEntity(url, request, String.class); } catch (Exception e) { System.out.println("Server not available: " + e.getMessage()); return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); } } public static ResponseEntity getRequest(String url) { try { return restTemplate.getForEntity(url, String.class); } catch (Exception e) { System.out.println("Server not available: " + e.getMessage()); return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); } } public static ResponseEntity putRequest(String url, Word word) { try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity request = new HttpEntity<>(word, headers); restTemplate.put(url, request); return new ResponseEntity<>("PUT successful", HttpStatus.OK); } catch (Exception e) { System.out.println("Server not available: " + e.getMessage()); return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); } } public static ResponseEntity deleteRequest(String url) { try { restTemplate.delete(url); return new ResponseEntity<>("DELETE successful", HttpStatus.OK); } catch (Exception e) { System.out.println("Server not available: " + e.getMessage()); return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE); } } }