httpclient 实现https请求

时间:2025-04-25 07:22:48

httpclient 实现https请求,4.4版本之后,工具类如下:


 

package ;

import ;
import ;
import ;
import ;
import ;
import .X509Certificate;
import ;
import ;
import ;
import ;

import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import org.;
import org.;

public class HttpsUtils {
	private static Logger logger = ();
	static CloseableHttpClient httpClient;
	static CloseableHttpResponse httpResponse;

	public static CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			HostnameVerifier hostnameVerifier = ;
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
			return ().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			();
		} catch (NoSuchAlgorithmException e) {
			();
		} catch (KeyStoreException e) {
			();
		}
		return ();

	}

	/**
	 * 发送https请求
	 * 
	 * @param jsonPara
	 * @throws Exception
	 */
	public static String sendByHttp(Map<String, Object> params, String url) {
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> listNVP = new ArrayList<NameValuePair>();
			if (params != null) {
				for (String key : ()) {
					(new BasicNameValuePair(key, (key).toString()));
				}
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listNVP, "UTF-8");
			("创建请求httpPost-URL={},params={}", url, listNVP);
			(entity);
			httpClient = ();
			httpResponse = (httpPost);
			HttpEntity httpEntity = ();
			if (httpEntity != null) {
				String jsObject = (httpEntity, "UTF-8");
				return jsObject;
			} else {
				return null;
			}
		} catch (Exception e) {
			();
			return null;
		} finally {
			try {
				();
				();
				("请求流关闭完成");
			} catch (IOException e) {
				("请求流关闭出错");
				();
			}
		}
	}

	public static void main(String[] args) throws Exception {
		Map<String, Object> map = new HashMap<>();
		("authCode", "FX:123");
		("userName", "jianghaida");
		("pwd", "jianghaida");
		

		((map, "https://localhost:8010/postDoc"));;
	}
}
4.4之前的版本  可参考

/rongyongfeikai2/article/details/41659353/

代码都以测试过,可用