RestTemplate常用方法

RestTemplate带参的get请求

    public static void main(String[] args) {
        String url = "https://dev.citconpay.com/payment/pay";
        // 请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        // OAuth 2.0认证
        requestHeaders.add("Authorization", "5753BC63A2FAC434FFD2");
        //Param 封装url
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("amount", "1")
                .queryParam("currency", "USD")
                .queryParam("vendor", "generic")
                .queryParam("reference", "83847328742384247832");
        //HttpEntity
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestHeaders);
        //get
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, requestEntity, String.class);
        System.out.println(responseEntity.getBody());
    }

RestTemplate带参的post请求

    public static void main(String[] args) {
        String url = "https://dev.citconpay.com/payment/pay";
        // 请求头
        HttpHeaders requestHeaders = new HttpHeaders();
        // OAuth 2.0认证
        requestHeaders.add("Authorization", "5753BC63A2FAC434FFD2");
        //body
        MultiValueMap<String, Object> body= new LinkedMultiValueMap<>();
        body.add("amount", "1");
        body.add("currency", "USD");
        body.add("vendor", "generic");
        body.add("reference", "83847328742384247832");
        //HttpEntity
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(body,requestHeaders);
        //get
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        System.out.println(responseEntity.getBody());
    }

你可能感兴趣的:(学习笔记)