欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

RestTemplate发送带请求头的Json的Post请求Utils工具类

程序员文章站 2022-05-04 08:43:48
RestTemplate发送带请求头的Json的Post请求import java.time.Duration;import java.util.Map;import java.util.Optional;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.web.client.RestTemplateBuilder;import org.springframewor...

RestTemplate发送带请求头的Json的Post请求

import java.time.Duration;
import java.util.Map;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class HttpPostJson {

    // 设置请求超时时间10s
    private static final RestTemplate restTemplate = new RestTemplateBuilder()
        .setConnectTimeout(Duration.ofSeconds(10L)).setReadTimeout(Duration.ofSeconds(10L)).build();
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(HttpPostJson.class);

    /**
     * 通过url 请求头信息 请求参数信息 Post请求
     * @param url 访问Url
     * @param headers 请求头信息
     * @param parameters 请求参数
     * @param 动态类型
     * @return Optional<T> 返回值
     */
    public static final <T> Optional<T> postJson(@Nullable String url, Map<String, String> headers,
        @Nullable Map<String, Object> parameters, @Nullable Class<T> clazz) {

        HttpHeaders httpHeaders = new HttpHeaders();

        if (null != headers) {
            headers.forEach((key, value) -> {
                httpHeaders.add(key, value);
            });
        }

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<Map<String, Object>>(parameters, httpHeaders);

        ResponseEntity<T> responseEntity = null;
        try {
            responseEntity = restTemplate.postForEntity(url, httpEntity, clazz);
        } catch (RestClientException e) {
            // 打印异常日志
            logger.error(e.getMessage());
        }

        if (null == responseEntity) {
            logger.error("返回结果为空");
        } else if (200 == responseEntity.getStatusCodeValue()) {
            return Optional.of(responseEntity.getBody());
        } else {
            logger.error(responseEntity.getStatusCode().toString());
        }

        return Optional.empty();
    }

}

 

本文地址:https://blog.csdn.net/liwenyang1992/article/details/107674491