编程语言
首页 > 编程语言> > java工具类HttpUtil,支持http和https(忽略Certification)

java工具类HttpUtil,支持http和https(忽略Certification)

作者:互联网

开发过程中,将springboot应用改为https请求后,普通的http请求会报错,原因是卡在证书认证了,添加了忽略认证的请求方式。

import java.util.Map;

import okhttp3.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import okhttp3.FormBody.Builder;

public class HttpUtil {
	static final Logger logger = LogManager.getLogger(HttpUtil.class.getName());

	/**
	 * post请求
	 * @param url url
	 * @param data postData
	 * @return response.body().string()
	 */
	public static String post(String url, Map<String, Object> data) {
		OkHttpClient httpClient = new OkHttpClient();
		
		RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
		Request request = new Request.Builder().url(url).post(requestBody).build();
		Response response = null;
		try {
			Call call = httpClient.newCall(request);
			response = call.execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}

	/**
	 * put请求
	 * @param url url
	 * @param data putData
	 * @return response.body().string()
	 */
	public static String put(String url, Map<String, Object> data) {
		OkHttpClient httpClient = new OkHttpClient();
		
		RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
		Request request = new Request.Builder().url(url).method("PUT", requestBody).build();
		Response response = null;
		try {
			Call call = httpClient.newCall(request);
			response = call.execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}

	/**
	 * post表单请求
	 * @param url url
	 * @param data postData
	 * @return response.body().string()
	 */
	public static String formPost(String url, Map<String, String> data) {
		OkHttpClient httpClient = new OkHttpClient();
		Builder builder = new FormBody.Builder();
		for (String key : data.keySet()) {
			builder.add(key, data.get(key));
		}
		Request request = new Request.Builder().url(url).post(builder.build()).build();
		Response response = null;
		try {
			Call call = httpClient.newCall(request);
			response = call.execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}

	/**
	 * get请求
	 * @param url url
	 * @return response.body().string()
 	 */
	public static String get(String url) {
		OkHttpClient httpClient = new OkHttpClient();
		
		Request request = new Request.Builder().url(url).build();
		Response response = null;
		try {
			response = httpClient.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}

	/**
	 * get请求忽略ssl认证
	 * @param url url
	 * @return response.body().string()
	 */
	public static String getIgnoreCertification(String url) {
		Request request = new Request.Builder().url(url).build();

		Response response = null;
		try {
			response = OKHttpClientBuilder.buildOKHttpClient()
					.build()
					.newCall(request)
					.execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}

	/**
	 * post请求忽略ssl认证
	 * @param url url
	 * @param data postData
	 * @return response.body().string()
	 */
	public static String postIgnoreCertification(String url, Map<String, Object> data) {

		RequestBody requestBody = RequestBody.create(MediaType.get("application/json"), JSON.toJSONString(data));
		Request request = new Request.Builder().url(url).post(requestBody).build();
		Response response = null;
		try {
			response = OKHttpClientBuilder.buildOKHttpClient()
					.build()
					.newCall(request)
					.execute();
			if (response.isSuccessful()) {
				return response.body().string();
			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
		}finally {
			if (response != null) {
				response.body().close();
				response.close();
			}
		}
		return null;
	}
}

OKHttpClientBuilder类

import okhttp3.OkHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * @Description: https请求忽略认证
 * @Author: wangzg
 * @Time: 2021/8/26
 */
public class OKHttpClientBuilder {

    public static OkHttpClient.Builder buildOKHttpClient() {
        try {
            TrustManager[] trustAllCerts = buildTrustManagers();
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            return builder;
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
            return new OkHttpClient.Builder();
        }
    }

    private static TrustManager[] buildTrustManagers() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };
    }
}

标签:body,return,Certification,url,https,new,java,null,response
来源: https://www.cnblogs.com/wangzg97/p/15294246.html