傳送GET請求 示例

我的寵物-王小兔發表於2020-11-26

/**
* 傳送GET請求
* @param url 請求地址
* @param param 請求引數
* @param headers
* @return
*/
private String requestByGet(String url,Map<String, String> param,HttpHeaders headers){
//header填充
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity<MultiValueMap<String,Object>>(null,headers);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    ResponseEntity<String> responseEntity;
    //如果存在引數
    if(!param.isEmpty()){
        for (Map.Entry<String,String> e:
                param.entrySet()) {
            //構建查詢引數
            builder.queryParam(e.getKey(),e.getValue());
        }
        URI uri = builder.build().encode().toUri();
        restClient = new RestTemplate();
        responseEntity  =restClient.exchange(uri,HttpMethod.GET,request,String.class);
    }else{
        responseEntity=restClient.exchange(url,HttpMethod.GET,request,String.class);
    }
    return responseEntity.getBody();
}

其中restClient 物件例項是DI進入的,本例直接new了,看官們注意…

相關文章