spring boot:从零开始搭建一个项目 - day 6 RestTemplate实现Post、Get请求

spring boot:从零开始搭建一个项目 - day 6 RestTemplate实现Post、Get请求

由于微信小程序开发需要从微信端使用get请求获取信息,就在网上找资料如何建立Http连接,鉴于本次开发是私底下的总结,就不想用HttpClient建立连接(主要还是太麻烦了啊!!!),当然也是因为看到了Spring中的RestTemplate类,感觉好用到爆。

一、getForEntity

众所周知,微信开发是需要从服务器端请求的,当然我没有服务器=。=,但不妨碍我模拟一个返回啊。
先丢代码!


    /**
     * 调用外部接口方法
     *
     * @param methUrl 接口地址
     * @param object  参数对象(单参数)
     * @param <T>
     * @return JSON对象
     */
    public static <T> JSONObject httpGetRequestMethod(String methUrl, T object) {
    
    
        HttpHeaders headers = new HttpHeaders();
        //设置Content-Type为application/json
        headers.setContentType(MediaType.APPLICATION_JSON);
        //若要使用parseObject()方法,使用LinkedHashMap对象较为稳健
        LinkedHashMap<String, String> map = null;
        //拼接一下url
        if(object != null){
    
    
            map = JSON.parseObject(JSON.toJSONString(object), new TypeReference<LinkedHashMap<String, String>>(){
    
    });
            StringBuffer url = new StringBuffer(methUrl);
            int i = 0;
            for(String key : map.keySet()){
    
    
                if(i == 0) {
    
    
                    url.append("?");
                } else {
    
    
                    url.append("&");
                }
                url.append(key)
                        .append("={")
                        .append(key)
                        .append("}");
                i++;
            }
            methUrl = url.toString();
        }
        ResponseEntity<JSONObject> response = new RestTemplate().getForEntity(methUrl, JSONObject.class,map);
        JSONObject resultJ = response.getBody();
        return resultJ;
    }
		//若要使用parseObject()方法,使用LinkedHashMap对象较为稳健
        LinkedHashMap<String, String> map = null;

同学们,看这个代码块,实际上搜到的更多要求创建MultiValueMap对象,因为跟踪Post请求的时候可以看到使用了HttpEntity包装headers和body
在这里插入图片描述

map = JSON.parseObject(JSON.toJSONString(object), new TypeReference<LinkedHashMap<String, String>>(){
    
    });

我这里为了写得bigger高点,加入泛型把方法写成了通用方法,但是使用fastjson转为MultiValueMap的时候报错,跟踪代码得到原因未明。if判断的时候直接进入第一个代码段,这是反序列化失败了吧?是吧?是失败了吧????迫不得已只能转为LinkedHashMap。反正都能用
在这里插入图片描述

测试一下

请求的方法
在这里插入图片描述
模拟的方法
在这里插入图片描述

二、postForEntity

Post方法同上

/**
     * 调用外部接口方法
     *
     * @param methUrl 接口地址
     * @param object  参数对象(单参数)
     * @param <T>
     * @return JSON对象
     */
    public static <T> JSONObject httpPostRequestMethod(String methUrl, T object) {
    
    
        HttpHeaders headers = new HttpHeaders();
        //设置Content-Type为application/json
        headers.setContentType(MediaType.APPLICATION_JSON);
        //若要使用postForEntity()方法,使用MultiValueMap对象较为稳健
        LinkedHashMap<String, String> map = JSON.parseObject(JSON.toJSONString(object),new TypeReference<LinkedHashMap<String, String>>(){
    
    });
        HttpEntity<LinkedHashMap<String, String>> linkedMap = new HttpEntity(map, headers);
        ResponseEntity<JSONObject> response = new RestTemplate().postForEntity(methUrl, linkedMap, JSONObject.class);
        JSONObject resultJ = response.getBody();
        return resultJ;
    }

写在最后,其实可以使用postForObject以及getForObject直接获取返回体,就不需要response.getBody()多此一举。以get为例: 因为post没写例子,大概能用吧

//        ResponseEntity<JSONObject> response = new RestTemplate().getForEntity(methUrl, JSONObject.class,map);
//        JSONObject resultJ = response.getBody();
        
        JSONObject resultJ = new RestTemplate().getForObject(methUrl, JSONObject.class,map);
        return resultJ;

猜你喜欢

转载自blog.csdn.net/qq_16253859/article/details/106268704