RestTemplate请求工具类

package com.nikooh.manage.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.Objects;
import java.util.Optional;

/**
 * @Description: Rest请求工具类
 * @Author: nikooh
 * @Date: 2020/08/18 : 11:16
 */
public final class RestClient {

    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RestClient.class);

    /**
     * restTemplate
     */
    private static RestTemplate restTemplate;

    /**
     * 请求entity
     */
    private HttpEntity httpEntity;

    /**
     * 请求头
     */
    private HttpHeaders httpHeaders;

    /**
     * 请求contentType
     */
    private String contentType;

    /**
     * 请求参数
     */
    private HashMap<String, Object> params;

    /**
     * 空参构造
     */
    private RestClient() {
    }

    static {
        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
                = new HttpComponentsClientHttpRequestFactory();
        //10s
        httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
        //30s
        httpComponentsClientHttpRequestFactory.setReadTimeout(30000);

        restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
    }

    /**
     * 创建RestClient
     *
     * @return RestClient
     */
    public static RestClient build() {
        return new RestClient();
    }

    /**
     * 设置请求头
     *
     * @param headerName  请求头名称
     * @param headerValue 请求头值
     * @return this
     */
    public RestClient addHeader(String headerName, String headerValue) {
        this.httpHeaders = Optional.ofNullable(this.httpHeaders).orElse(new HttpHeaders());
        this.httpHeaders.add(headerName, headerValue);
        return this;
    }

    /**
     * 设置请求体
     *
     * @param paramName  参数名称
     * @param paramValue 参数值
     * @return this
     */
    public RestClient addParams(String paramName, Object paramValue) {
        this.params = Optional.ofNullable(this.params).orElse(new HashMap<>());
        this.params.put(paramName, paramValue);
        return this;
    }

    /**
     * 设置contentType
     *
     * @param contentType 类型
     * @return this
     */
    public RestClient addContentType(String contentType) {
        if (StringUtils.isBlank(contentType)) {
            LOGGER.error("RestClient.build---------->content-Type can not be empty!");
            throw new RuntimeException("content-Type can not be empty!");
        }
        this.contentType = contentType;
        this.httpHeaders = Optional.ofNullable(this.httpHeaders).orElse(new HttpHeaders());
        this.httpHeaders.setContentType(MediaType.parseMediaType(contentType));

        return this;
    }

    /**
     * 构建HttpEntity
     */
    private void create() {
        if (Objects.isNull(this.params)) {
            LOGGER.error("RestClient.build---------->body must be not empty!");
            throw new RuntimeException("body must be not empty!");
        }
        if (Objects.isNull(contentType) || ContentType.APPLICATION_JSON.getMimeType().equals(contentType)) {
            this.addContentType(ContentType.APPLICATION_JSON.getMimeType());
            JSONObject jsonObject = new JSONObject();
            for (String s : params.keySet()) {
                try {
                    jsonObject.put(s, params.get(s));
                } catch (JSONException e) {
                    LOGGER.error("RestClient.build---------->JSONException:[{}]", e.getMessage());
                    throw new JSONException("params set error!");
                }
            }
            String body = jsonObject.toString();
            this.httpEntity = new HttpEntity<>(body, this.httpHeaders);
        } else if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
            MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
            for (String s : params.keySet()) {
                formData.add(s, params.get(s));
            }
            this.httpEntity = new HttpEntity<>(formData, this.httpHeaders);
        } else {
            LOGGER.error("RestClient.build---------->content-Type not supported!");
            throw new RuntimeException("content-Type not supported!");
        }
    }

    /**
     * get请求
     *
     * @param url   url
     * @param clazz T.class
     * @param <T>   T
     * @return T
     */
    public <T> T get(String url, Class<T> clazz) {
        ResponseEntity<T> entity = restTemplate.getForEntity(url, clazz, this.params);
        if (HttpStatus.OK.equals(entity.getStatusCode())) {
            return entity.getBody();
        } else {
            LOGGER.error("RestClient.get---------->get error! status:[{}]", entity.getStatusCode().toString());
            throw new RuntimeException(entity.getStatusCode().toString());
        }
    }

    /**
     * post请求
     *
     * @param url   url
     * @param clazz t.class
     * @param <T>   T
     * @return T
     */
    public <T> T post(String url, Class<T> clazz) {
        this.create();
        ResponseEntity<T> entity = restTemplate.postForEntity(url, this.httpEntity, clazz);
        if (HttpStatus.OK.equals(entity.getStatusCode())) {
            return entity.getBody();
        } else {
            LOGGER.error("RestClient.post---------->post error! status:[{}]", entity.getStatusCode().toString());
            throw new RuntimeException(entity.getStatusCode().toString());
        }
    }

    /**
     * exchange
     *
     * @param url
     * @param clazz
     * @param method
     * @param <T>
     * @return
     */
    public <T> T exchange(String url, Class<T> clazz, HttpMethod method) {
        this.create();
        ResponseEntity<T> entity = restTemplate.exchange(url, method, this.httpEntity, clazz);
        if (HttpStatus.OK.equals(entity.getStatusCode())) {
            return entity.getBody();
        } else {
            log.error("RestClient.exchange---------->exchange error! status:[{}]", entity.getStatusCode().toString());
            throw new RuntimeException(entity.getStatusCode().toString());
        }
    }

}


使用方法

        JSONObject result = RestClient.build()
                .addContentType("application/json")
                .addHeader("Authorization","Bearer bbc56d43-ec30-4ab5-af8c-516a5e739")
                .addHeader("scope","web")
                .addParams("id",1)
                .addParams("name","zhangsan")
                .post("https://www.baidu.com", JSONObject.class);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值