1. 程式人生 > 其它 >RestTemplat的封裝工具類

RestTemplat的封裝工具類

package util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ClassName RestTemplateUtil
 * @Author Eangaie
 * DATE 2021/6/22 0022 16:55
 * @Version 1.0
 **/
public class RestTemplateUtil {

    /**
     * @return java.lang.String
     * @Author Ean
     * @Description get請求,引數需要使用{}在url裡邊佔位,param傳過來的必須key跟引數一致
     * @Date 17:06 2021/6/22 0022
     * @Param [url, param]
     **/
    public static String getForObj(String url, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject(url, String.class, param);
        return res;
    }

    /**
     * @return java.lang.String
     * @Author Ean
     * @Description postform請求。用法跟getForObj一致
     * @Date 17:07 2021/6/22 0022
     * @Param [url, param]
     **/
    public static String postForObjForm(String url, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.postForObject(url, null, String.class, param);
        return res;
    }

    /**
     * @return java.lang.String
     * @Author Ean
     * @Description 發起post的json請求param引數物件可以傳null,否則跟postForObjForm用法一致。
     * @Date 17:11 2021/6/22 0022
     * @Param [url, body, param]
     **/
    public static String postForObjJson(String url, String body, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
        String res = restTemplate.postForObject(url, httpEntity,String.class, param);
        return res;
    }


    public static byte[] postForByteArr(String url, String body, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
        byte[] res = restTemplate.postForObject(url, httpEntity,byte[].class, param);
        return res;
    }
}

最後一個函式是用來請求小程式碼的,返回的是位元組型別均測試可用