通用Http(s) GET、POST、PUT请求方法

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.model.RestResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    static {
        try {
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
        }
    }

    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        trustAllCerts[0] = new TrustAllManager();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    }


    private static final int connect_timeout = 20 * 1000;
    private static final int read_timeout = 20 * 1000;

    private static final RestTemplate rest = new RestTemplate();
    private static final RestTemplate httpsRest = new RestTemplate();

    static RestTemplate restTemplate() {
        return rest;
    }

    static RestTemplate httpsRestTemplate() {
        return httpsRest;
    }


    public static ResponseEntity<RestResult> sendRestRequest(String url, Object object, HttpMethod method, HttpHeaders httpHeaders) {
        if (method == null) {
            return null;
        }
        String requestId = UUID.randomUUID().toString().replace("-", "").toLowerCase();;
        logger.info("[requestId={}],[RestTemplate]Invoke {},method: {}", requestId, method, url);
        httpHeaders.add("X-LC-RequestId", requestId);

        RestTemplate rest = null;
        if (url.startsWith("https://")) {
            rest = httpsRestTemplate();
        } else {
            rest = restTemplate();
        }

        if (rest == null) {
            return null;
        }
        HttpEntity<Object> entity = new HttpEntity<>(object, httpHeaders);

        try {
            ResponseEntity<Object> response = rest.exchange(url, method, entity, Object.class);
            if (response == null) {
                throw new RestClientException("response is null");
            }
            RestResult restResult = new RestResult(response.getStatusCodeValue(), response.getBody());
            HttpStatus statusCode = HttpStatus.OK.value() != response.getStatusCodeValue() && null == HttpStatus.resolve(response.getStatusCodeValue()) ? HttpStatus.INTERNAL_SERVER_ERROR : response.getStatusCode();
            ResponseEntity<RestResult> responseSuc = new ResponseEntity<>(restResult, statusCode);
            return responseSuc;
        } catch (HttpServerErrorException serverException) {
            logger.error("RestTemplateUtil,HttpServerErrorException:{}", serverException);
            RestResult restResult = new RestResult();
            try {
                restResult = JSONObject.parseObject(serverException.getResponseBodyAsString(), RestResult.class);
            } catch (Exception error) {
                logger.warn("getResponseBodyAsString,parse:{}", error);
            }
            if (restResult == null || restResult.getMessage() == null) {
                restResult = new RestResult(serverException.getStatusCode().value(), serverException.getResponseBodyAsString());
            }
            ResponseEntity<RestResult> responseSuc = new ResponseEntity<>(restResult, serverException.getStatusCode());
            return responseSuc;
        } catch (HttpClientErrorException e) {
            logger.error("RestTemplateUtil,HttpClientErrorException:{}", e);
            RestResult restResult = new RestResult();
            try {
                restResult = JSONObject.parseObject(e.getResponseBodyAsString(), RestResult.class);
            } catch (Exception error) {
                logger.warn("getResponseBodyAsString,parse:{}", error);
            }
            if (restResult == null || restResult.getMessage() == null) {
                restResult = new RestResult(e.getStatusCode().value(), e.getResponseBodyAsString());
            }
            ResponseEntity<RestResult> body = new ResponseEntity<>(restResult, e.getStatusCode());
            return body;
        } catch (RestClientException var13) {
            logger.error("RestTemplateUtil,RestClientException:{}", var13);
            RestResult body = new RestResult(HttpStatus.EXPECTATION_FAILED.value(), "Rest未知异常");
            ResponseEntity<RestResult> response = new ResponseEntity<>(body, HttpStatus.EXPECTATION_FAILED);
            return response;
        }
    }
}
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class TrustAllManager implements X509TrustManager {


    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}


调用示例:

public static void main(String[] args) {
    String url = "https://127.0.0.1:8320/device-management/devicesManager/devices/9142431916165312";
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-Subject-Token", "S4NbecfYB19QUJHT4T8M7G_LSEQbXrepy4SgYHXnSvWeA6jr1soIbvuObNYF9ciZ0");
    Map map = new HashMap();
    ResponseEntity<RestResult> responseEntity = HttpUtil.sendRestRequest(url, map, HttpMethod.GET, headers);
    //返回结果
    Object resObj = responseEntity.getBody().getData();
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值