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(HEADERSJ),
                String.class).getBody();
    }

    /**
     * header为:json
     *
     * @param url
     * @param requestParams
     * @return
     * @throws Exception
     */
    public static String postForJSON(String url, Object requestParams) throws Exception {
        HttpEntity 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 map) {
        MultiValueMap reqMap = new LinkedMultiValueMap<>();
        for (Map.Entry entry : map.entrySet()) {
            reqMap.add(entry.getKey(), entry.getValue());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        String res;
        try {
            HttpEntity> request = new HttpEntity<>(reqMap, headers);
            ResponseEntity 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 requestParams) throws Exception {
        LinkedMultiValueMap body = new LinkedMultiValueMap();
        for (String key : requestParams.keySet()) {
            body.add(key, requestParams.get(key));
        }
        HttpEntity entity = new HttpEntity(body, HEADERSF);
        JSONObject responseJson;
        try {
            responseJson = REST_TEMPLATE.postForObject(url, entity, JSONObject.class);
        } catch (Exception e) {
            throw e;
        }
        return responseJson;
    }

}
 
  

 

你可能感兴趣的:(ssm)