ResrTemplate GET 无需手动拼接url参数

0、最初的写法(这样写也是可以的,就是太麻烦了,可读性不好)

 String param = "name={0}&idcard={1}&phone={2}&sex={3}&national={4}&birthday={5}&address={6}" +
                "&issuance=&effective=&effective_end=&front_photo=&back_photo=&scene_photo={7}&card_type=身份证&mopenid=";
        String sex = "";
        if (usr.getAuthSex() == 0) {
            sex = "男";
        } else if (usr.getAuthSex() == 1) {
            sex = "女";
        }
        param = MessageFormat.format(param, usr.getAuthName(), usr.getAuthIdCard(), usr.getUserPhone(), sex, usr.getAuthNation(),
                usr.getAuthBirthday(), usr.getAuthAddress(), usr.getAuthHoldphoto());
        HttpHeaders headers = new HttpHeaders();

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();


        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        headers.add("Authorization", token);

        //JSONObject codeRes = restTemplate.getForObject(url, JSONObject.class, httpEntity);
        //这里使用上面的方法还无法实现,得用URLConnection。。。所以我就不写了

1、错误的方法:


Map<String, String> params = new HashMap<String, String>();
params.put("sex", "男");
params.put("national", "中国");
params.put("birthday", "199002190");

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity entity = new HttpEntity(headers);

HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);

这样写错误的原因是请求后无法获取到参数

2、正确的写法

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("msisdn", msisdn)
        .queryParam("sex", "男")
        .queryParam("national", "中国")
        .queryParam("birthday", "199002190");

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

HttpEntity<?> entity = new HttpEntity<>(headers);

HttpEntity<String> response = restTemplate.exchange(
        builder.build().encode().toUri(), 
        HttpMethod.GET, 
        entity, 
        String.class);

可以将builder.build().toUri()中的内容打印出来看一下,就是get请求时的url地址,参数全部拼接在了url上, 如下:

http:/localhost:8026/api/RealNameAdd?name=李狗蛋&idcard=xxx&phone=xxx&sex=男&national=中国&birthday=199002190&address=xxx&issuance=1&effective=&effective_end=&front_photo=&back_photo=&scene_photo=xxx&card_type=身份证&mopenid=2100222222

这个问题坑了我很久,百度一直查不到,后来google才找到的。既然如此写下来吧。也许有人百度能从我这里找到呢。

查找资源参考自:https://codeday.me/bug/20170708/41709.html

猜你喜欢

转载自blog.csdn.net/wokenshin/article/details/80971115