1. 程式人生 > >springboot傳送http請求

springboot傳送http請求

    public static String HttpRestClient(String url, HttpMethod method, MultiValueMap<String, String> params) throws IOException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000);
        requestFactory.setReadTimeout(10*1000);
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //  請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  執行HTTP請求
        ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
        return response.getBody();
    }
                //api url地址
                String url = "";
                //post請求
                HttpMethod method =HttpMethod.GET;
                // 封裝引數,千萬不要替換為Map與HashMap,否則引數無法傳遞
                MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
                //傳送http請求並返回結果
                String result = HttpUtil.HttpRestClient(url,method,params);