httppost请求工具类(jar)

以前也手写过http工具类,纯原生的。 但有些jar里面也是有封装hhtp请求的,今天再写一个别人封装好的demo,用到的架包是spring-web-5.2.5.jar

工具类如下

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;
    }
}

接收对象

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 工具类

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;
		}
	}
}

用这个需要注意的地方就是https的请求了, 如果是服务器上没有安装ssl证书或者本地测试,而你请求的地址是https,就记得加上SslUtils.ignoreSsl();这一行代码,并且要写在发起请求之前。不然请求过去会报错,错误信息大致如下:

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

猜你喜欢

转载自blog.csdn.net/qq_29539827/article/details/130371468