优雅的在spring boot上使用RestTemplate请求远程接口

RestTemplate的有三种方法:1、postForObject方法 2、postForEntity方法 3、exchange方法

区别:postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。exchange方法和postForEntity类似,但是更灵活,exchange还可以发送get请求。

1.工具类,可以发送get和post请求

/**
     * 优雅的向目的URL发送远程请求
     * @param url           目的url
     * @param requestMethod 请求方法
     * @param params        发送的参数
     * @return BaseResponse
     */
    public static LinkedHashMap sendRemoteRequest(String url, String requestMethod, Map<String, Object> params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = null;
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, Object>> requestEntity = null;
        //执行HTTP请求,将返回的结构使用BaseResponse类格式化
        ResponseEntity<Object> response = null;
        //get请求
        if (requestMethod.equalsIgnoreCase("get")) {
            method = HttpMethod.GET;
            requestEntity = new HttpEntity<>(null, headers);
            response = client.exchange(url, method, requestEntity, Object.class, params);
            //post请求
        } else if (requestMethod.equalsIgnoreCase("post")) {
            method = HttpMethod.POST;
            requestEntity = new HttpEntity<>(params, headers);
            response = client.exchange(url, method, requestEntity, Object.class);
        }
        return (LinkedHashMap) response.getBody();
    }

2.发送get请求,请求高德地图的地理编码接口

//获取门店地址
    public String getStoreAddress(String key,String address){
        String url = "https://restapi.amap.com/v3/geocode/geo?key={key}&address={address}}";
        Map<String,Object> map = new HashMap<>();
        map.put("key",key);
        map.put("address",address);
        //1、使用getForObject,并用实体类接收
//        String json = client.getForObject(url, String.class, map);
//        AddressVo addressVo = (AddressVo) JSON.toJSON(json);
        //2、使用exchange请求接口
        LinkedHashMap linkedHashMap  =  RestTemplateUtils.sendRemoteRequest(url,"get",map);
        if (linkedHashMap.get("info").equals("OK")){
            log.info("请求远程接口成功!");
        }else{
            log.info("请求远程接口失败!"+linkedHashMap);
        }
        List<LinkedHashMap> addressInfoList = (List) linkedHashMap.get("geocodes");
        return (String) addressInfoList.get(0).get("province");
    }

3.发送post请求

 public String getStoreInfo(String storeId){
        String url = " ";
        Map<String, Object> param = new HashMap<>();
        param.put("companyId", "");
        param.put("purchasingArea", "");
        param.put("purchasingCenterId", "");
        param.put("scale", "");
        param.put("storeId", storeId);
        param.put("storeName", "");
        param.put("storeStatus", "");
        param.put("pageNo", 1);
        param.put("pageSize", 10);
        param.put("endTime", null);
        param.put("startTime", null);
        //请求参数用JOSN类型也行
//        JSONObject postData = new JSONObject();
//        postData.put("companyId", "");
//        postData.put("purchasingArea", "");
//        postData.put("purchasingCenterId", "");
//        postData.put("scale", "");
//        postData.put("storeId", storeId);
//        postData.put("storeName", "");
//        postData.put("storeStatus", "");
//        postData.put("pageNo", 1);
//        postData.put("pageSize", 10);
//        postData.put("endTime", null);
//        postData.put("startTime", null);

        //1、用postForEntity方法请求,并用实体类接收,创建实体类太麻烦,不推荐
//        RestTemplate client = new RestTemplate();
//        JSONObject json = client.postForEntity(url, postData, JSONObject.class).getBody();
//        //StoreVO 是提前创建好的实体类,将返回的json中的result数据转换为StoreVO 格式
//        StoreVO storeVO = json.getObject("result", StoreVO.class);
//       String address = storeVO.getList().get(0).getAddress();
		//2、用exchange方法请求,并用LinkedHashMap 接收
        LinkedHashMap linkedHashMap  =   RestTemplateUtils.sendRemoteRequest(url,"post",param);
        if (linkedHashMap.get("code").equals("100")){
            log.info("请求远程接口成功!");
        }else{
            log.info("请求远程接口失败!"+linkedHashMap);
        }
        List list = (List) ((LinkedHashMap) linkedHashMap.get("result")).get("list");
        LinkedHashMap linkedHashMap1 = (LinkedHashMap) list.get(0);
        
        return (String) linkedHashMap1.get("address");
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值