httppost request tool class (jar)

I have also handwritten the http tool class before, which is purely native. But some jars also encapsulate hhtp requests. Today, I will write a demo packaged by others. The package used is spring-web-5.2.5.jar

Tools are as follows

package com.yulisao.util;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import com.yulisao.dto.HttpResponse;
import java.util.List;

/**
 * http post 请求工具类
 *
 * author yulisao
 * createDate 2023/4/14
 */
public class PostHttpUtils {
    
    

    /**
     * 发起post请求
     *
     * @param postUrl  请求地址
     * @param param  请求参数
     * @param <T>
     */
    public static <T> List<T> httpPost(String postUrl, T param) {
    
    
        try {
    
    
            // 头部参数设置
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("appName", "yourAppName");
            headers.set("version", "1.0.0");
            headers.set("timesamp", Long.toString(System.currentTimeMillis()));
            // more headers...

            // 请求体
            HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(param), headers);

            // 忽略SSL证书, 这样·本地无ssl证书也可以访问https
            SslUtils.ignoreSsl();

            RestTemplate restTemplate = new RestTemplate();
            // 当Factory为HttpComponentsClientHttpRequestFactory请求要求CA证书
            restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());

            // 初始化返回结果
            HttpResponse response = restTemplate.postForObject(postUrl, entity, HttpResponse.class);
            System.out.println("返回报文:{}" + JSON.toJSONString(response));

            if ("SUCCESS".equals(response.getCode())) {
    
    
                return response.getResult();
            } else {
    
    
                System.out.println("请求失败,错误原因:{}" + response.getMessage());
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        return null;
    }
}

recipient

package com.yulisao.dto;

import lombok.Data;

import java.util.List;

/**
 * 接口返回接收对象
 * author yulisao
 * createDate 2023/4/14
 */
@Data
public class HttpResponse<T> {
    
    

    // 返回状态码
    private String code;

    // 返回状态码
    private String message;

    // 返回状数据
    private List<T> result;
}

ssl tool class

package com.yulisao.util;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SslUtils {
    
    

	/**
	 * 忽略https请求的SSL证书(创建连接之前调用)
	 *
	 * @throws Exception
	 */
	public static void ignoreSsl() throws Exception {
    
    
		HostnameVerifier hv = new HostnameVerifier() {
    
    
			@Override
			public boolean verify(String urlHostName, SSLSession session) {
    
    
				return true;
			}
		};
		trustAllHttpsCertificates();
		HttpsURLConnection.setDefaultHostnameVerifier(hv);
	}

	public static void trustAllHttpsCertificates() throws Exception {
    
    
		TrustManager[] trustAllCerts = new TrustManager[1];
		TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		SSLContext sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	static class miTM implements TrustManager, X509TrustManager {
    
    
		@Override
		public X509Certificate[] getAcceptedIssuers() {
    
    
			return null;
		}

		public boolean isServerTrusted(X509Certificate[] certs) {
    
    
			return true;
		}

		public boolean isClientTrusted(X509Certificate[] certs) {
    
    
			return true;
		}

		@Override
		public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
    
    
			return;
		}
		@Override
		public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
    
    
			return;
		}
	}
}

The thing to pay attention to when using this is the HTTPS request. If there is no ssl certificate or local test installed on the server, and the address you request is https, remember to add this line of code and write it before initiating the request SslUtils.ignoreSsl();. Otherwise, the request will report an error in the past, and the error message is roughly as follows:

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Guess you like

Origin blog.csdn.net/qq_29539827/article/details/130371468
Recommended