RestTemplate SpringBoot HTTP

SpringBoot使用RestTemplate發送HTTP請求

東東 2021/03/29 18:17:55
106

RestTemplate 是在使用Spring Boot 開發傳案時一個非常好用的HTTP的工具。以往我們使用JAVA發送HTTP請求時總免不了要建立大量程式碼。但是使用RestTemplate則方便許多,程式碼也更為精簡。 

        例如以下以使用HttpURLConnection作為範例,發送JSON格式的請求,並將回傳資訊封裝為自訂議的ResponseObject

     public void httpDemo() throws JsonProcessingException {

        String url = "http://demo.com/demo";

        RequestObject requestObject = new RequestObject();

        requestObject.setName("XXX");

        requestObject.setPhoneNo("0987654321");

        requestObject.setEmail("Demo@demo.demo");

        ObjectMapper objectMapper = new ObjectMapper();

        String requestData = objectMapper.writeValueAsString(requestObject);

        try {

            String responseData = demoHttpURLConnection(url, requestData);

            ResponseObject responseObject = objectMapper.readValue(responseData, ResponseObject.class);

            log.info(responseObject.toString());

        } catch (Exception e) {

            // TODO: handle exception

        }

    }

 

    public String demoHttpURLConnection(String url, String requestData) throws IOException {

        URL endpoint = new URL(url);

        HttpURLConnection httpUrlConn = (HttpURLConnection) endpoint.openConnection();

        httpUrlConn.setRequestMethod("POST");

        httpUrlConn.setRequestProperty("Content-Type", "application/json");

        OutputStream outputStream = httpUrlConn.getOutputStream();

        byte[] input = requestData.getBytes("utf-8");

        outputStream.write(input, 0, input.length);

        int statusCode = httpUrlConn.getResponseCode();

        InputStream inputStream = null;

        if (statusCode == 200) {

            inputStream = httpUrlConn.getInputStream();

        } else {

            inputStream = httpUrlConn.getErrorStream();

        }

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

        StringBuilder response = new StringBuilder();

        String responseLine = null;

        while ((responseLine = bufferedReader.readLine()) != null) {

            response.append(responseLine.trim());

        }

        return response.toString();

    }

 以上程式碼包含request responseJSON轉換以及發送http的流程。接著示範使用 RestTemplate 

    public ResponseObject demoRestTemplate(String url, RequestObject requestObject) {

        RestTemplate restTemplate = new RestTemplate();

        ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);

        return responseObject;

    }

使用postForObject送與回傳都是已經用class封裝好的格式,流程變得更加精簡。除了post之外,也有getputpatchpatchdelete等等各種方法。或是使用exchange可以填入自己要用的HttpMethod。且可在HttpEntity添加請求標頭。

    public ResponseObject demoRestTemplate2(String url, RequestObject requestObject) {

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_JSON);

        headers.add("token", "NlXEt66fejIrQvIGampcPnLVdmIYVo0wdZf8T5H");

        HttpEntity<RequestObject> httpEntity = new HttpEntity<RequestObject>(requestObject, headers);

        ResponseEntity<ResponseObject> responseEntity = 
                restTemplate.exchange(url, HttpMethod.POST, httpEntity, ResponseObject.class);

        ResponseObject responseObject = responseEntity.getBody();

        return responseObject;

    }

        使用uri變量:

    public User getUser(String id) {

        RestTemplate restTemplate = new RestTemplate();

        User user = restTemplate.getForObject("http://demo/user/{id}", User.class, id);

        return user;

    }

如果有多個變量:

    public User getUser(String id, String name) {

        RestTemplate restTemplate = new RestTemplate();

        Map<String, String> uriVariables = new HashMap<String, String>();

        uriVariables.put("id", id);

        uriVariables.put("name", name);

        User user = restTemplate.getForObject("http://demo/user/{id}/{name}", User.class, uriVariables);

        return user;

    }

           設定timeout

    private SimpleClientHttpRequestFactory getClientHttpRequestFactory() {

        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();

        clientHttpRequestFactory.setConnectTimeout(1000);// 1秒

        return clientHttpRequestFactory;

    }

    private RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

        以上就是RestTemplate的一些簡單的使用方式,終於再也不用為了發HTTP請求而傷腦筋了!

東東