spring boot: Build a project from scratch - day 6 RestTemplate implements Post and Get requests

spring boot: Build a project from scratch - day 6 RestTemplate implements Post and Get requests

Since the development of WeChat applets needs to use the get request to obtain information from the WeChat side, I found information on the Internet on how to establish an Http connection. Since this development is a private summary, I don’t want to use HttpClient to establish a connection (mainly it is too much trouble!! !), of course, because I saw the RestTemplate class in Spring, and it feels so easy to use.

1. getForEntity

As we all know, WeChat development needs to be requested from the server side, of course I don't have a server=. =, but it does not prevent me from simulating a return.
Lose the code first!


    /**
     * 调用外部接口方法
     *
     * @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;

Students, look at this code block. In fact, more requests are found to create MultiValueMap objects, because when tracking Post requests, you can see that HttpEntity is used to wrap headers and body
insert image description here

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

In order to write a bigger point here, I added generics to write the method as a general method, but when using fastjson to convert to MultiValueMap, an error was reported, and the reason for the tracking code was unknown. When the if judges, it directly enters the first code segment. This means that the deserialization has failed, right? right? Did it fail? ? ? ? As a last resort, it can only be converted to LinkedHashMap. works anyway
insert image description here

have a test

The method that the requested method
insert image description here
mocks
insert image description here

二、postForEntity

Post method same as above

/**
     * 调用外部接口方法
     *
     * @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;
    }

Written at the end, in fact, you can use postForObject and getForObject to directly get the return body, so there is no need for response.getBody() to do more. Take get as an example: because the post did not write an example, it probably works

//        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;

Guess you like

Origin blog.csdn.net/qq_16253859/article/details/106268704