RestTemplateUtils的一個通用工具類

一、RestTemplate介紹

       RestTemplate是Spring提供的用於訪問Rest服務的客戶端,RestTemplate提供了多種便捷訪問遠程Http服務的方法,能夠大大提高客戶端的編寫效率。

        RestTemplate能大幅簡化了提交表單數據的難度,並且附帶了自動轉換JSON數據的功能,但只有理解了HttpEntity的組成結構(header與body),且理解了與uriVariables之間的差異,才能真正掌握其用法。

代碼如下:


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by${YangChao}on 2020/4/8
 */

public class RestTemplateUtils {
    public static final RestTemplate REST_TEMPLATE;
    /**
     * json
     */
    private static final HttpHeaders HEADERSJ;
    /**
     * form-data
     */
    private static final HttpHeaders HEADERSF;

    static {
        HttpComponentsClientHttpRequestFactory httpRequestFactory =
                new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create()
                        .setMaxConnTotal(200)
                        .setMaxConnPerRoute(100)
                        .build());
        httpRequestFactory.setConnectionRequestTimeout(100000);
        httpRequestFactory.setConnectTimeout(100000);
        httpRequestFactory.setReadTimeout(100000);
        REST_TEMPLATE = new RestTemplate(httpRequestFactory);

        HEADERSJ = new HttpHeaders();
        HEADERSJ.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HEADERSF = new HttpHeaders();
        HEADERSF.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    }

    public static String get(String url) {
        return REST_TEMPLATE.getForObject(url, String.class);
    }

    public static String request(String url, HttpMethod method) {
        return REST_TEMPLATE.exchange(url,
                method,
                new HttpEntity<String>(HEADERSJ),
                String.class).getBody();
    }

    /**
     * header爲:json
     *
     * @param url
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static String postForJSON(String url, Object requestParams) throws Exception {
        HttpEntity<Object> formEntity =
                new HttpEntity<>(JSONObject.toJSONString(requestParams), HEADERSJ);
        String responseJson;
        try {
            responseJson = REST_TEMPLATE.postForObject(url, formEntity, String.class);
        } catch (Exception e) {
            throw e;
        }
        return responseJson;
    }

    /**
     * post表單請求
     *
     * @param url
     * @param map
     * @return
     */
    public static String postFormData(String url, Map<String, String> map) {
        MultiValueMap<String, String> reqMap = new LinkedMultiValueMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            reqMap.add(entry.getKey(), entry.getValue());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        String res;
        try {
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(reqMap, headers);
            ResponseEntity<String> response = REST_TEMPLATE.postForEntity(url, request, String.class);
            res = response.getBody();
        } catch (Exception e) {
            throw e;
        }
        return res;
    }

    /**
     * header爲:form-data
     *
     * @param url
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static JSONObject postForForm(String url, Map<String, ? extends Object> requestParams) throws Exception {
        LinkedMultiValueMap body = new LinkedMultiValueMap();
        for (String key : requestParams.keySet()) {
            body.add(key, requestParams.get(key));
        }
        HttpEntity<String> entity = new HttpEntity(body, HEADERSF);
        JSONObject responseJson;
        try {
            responseJson = REST_TEMPLATE.postForObject(url, entity, JSONObject.class);
        } catch (Exception e) {
            throw e;
        }
        return responseJson;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章