HttpClient4.5 SSL访问工具类
要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,最后笔者干脆自己封装了一个访问HTTPS并绕过证书工具类。
主要是基于新版本HttpClient 4.5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | /** 解决httpClient对https请求报不支持SSLv3问题. JDK_HOME/jrebcurity/java.security 文件中注释掉: jdk.certpath.disabledAlgorithms=MD2 jdk.tls.disabledAlgorithms=DSA(或jdk.tls.disabledAlgorithms=SSLv3) */ public class HttpsUtil { public static CloseableHttpClient createClient() throws Exception{ TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] xc, String msg) throws CertificateException { return true ; } }; SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(trustStrategy); HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() { @Override public boolean verify(String name, SSLSession session) { return true ; } }; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build(), new String[] { "SSLv2Hello" , "SSLv3" , "TLSv1" , "TLSv1.1" , "TLSv1.2" }, null , hostnameVerifierAllowAll); HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest( IOException exception, int executionCount, HttpContext context) { //重试设置 if (executionCount >= 5 ) { // Do not retry if over max retry count return false ; } if (exception instanceof InterruptedIOException) { // Timeout return false ; } if (exception instanceof UnknownHostException) { // Unknown host return false ; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false ; } if (exception instanceof SSLException) { // SSL handshake exception return false ; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { return true ; } return false ; } }; RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout( 120000 ) .setSocketTimeout( 120000 ) //超时设置 .build(); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .setRetryHandler(myRetryHandler) //重试设置 .setDefaultRequestConfig(requestConfig) .build(); return httpclient; } public static String get(String url) throws Exception { return get(url, null , null ); } public static String get(String url,Map<String, String> header,Map<String, String> outCookies) throws Exception { String body = "" ; String Encoding = "utf-8" ; CloseableHttpClient client = createClient(); try { CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); // 创建get方式请求对象 HttpGet httpGet = new HttpGet(url); if (header!= null ){ if (header.get( "Accept" )!= null ) httpGet.setHeader( "Accept" , header.get( "Accept" )); if (header.get( "Cookie" )!= null ) httpGet.setHeader( "Cookie" , header.get( "Cookie" )); if (header.get( "Accept-Encoding" )!= null ) httpGet.setHeader( "Accept-Encoding" , header.get( "Accept-Encoding" )); if (header.get( "Accept-Language" )!= null ) httpGet.setHeader( "Accept-Language" , header.get( "Accept-Language" )); if (header.get( "Host" )!= null ) httpGet.setHeader( "Host" , header.get( "Host" )); if (header.get( "User-Agent" )!= null ) httpGet.setHeader( "User-Agent" , header.get( "User-Agent" )); if (header.get( "x-requested-with" )!= null ) httpGet.setHeader( "x-requested-with" , header.get( "x-requested-with" )); if (header.get( "Encoding" )!= null ) Encoding =header.get( "Encoding" ); } System.out.println( "请求地址:" + url); // 执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = client.execute(httpGet,localContext); // 获取结果实体 try { // 如果需要输出cookie if (outCookies!= null ){ List<Cookie> cookies = cookieStore.getCookies(); for ( int i = 0 ; i < cookies.size(); i++) { outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue()); } } HttpEntity entity = response.getEntity(); System.out.println( "返回:" + response.getStatusLine()); if (entity != null ) { // 按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, Encoding); // System.out.println("返回:"+body); } } finally { response.close(); } } finally { client.close(); } return body; } public static String post(String url, Map<String, String> params) throws Exception { return post(url, params, null , null ); } public static String post(String url, Map<String, String> params, Map<String, String> header,Map<String, String> outCookies) throws Exception { String body = "" ; String encoding = "utf-8" ; String contentType= "text/html" ; CloseableHttpClient client = createClient(); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); try { // 创建post方式请求对象 HttpPost httpPost = new HttpPost(url); if (header!= null ){ if (header.get( "Accept" )!= null ) httpPost.setHeader( "Accept" , header.get( "Accept" )); if (header.get( "Cookie" )!= null ) httpPost.setHeader( "Cookie" , header.get( "Cookie" )); if (header.get( "Accept-Encoding" )!= null ) httpPost.setHeader( "Accept-Encoding" , header.get( "Accept-Encoding" )); if (header.get( "Accept-Language" )!= null ) httpPost.setHeader( "Accept-Language" , header.get( "Accept-Language" )); if (header.get( "Host" )!= null ) httpPost.setHeader( "Host" , header.get( "Host" )); if (header.get( "User-Agent" )!= null ) httpPost.setHeader( "User-Agent" , header.get( "User-Agent" )); if (header.get( "x-requested-with" )!= null ) httpPost.setHeader( "x-requested-with" , header.get( "x-requested-with" )); if (header.get( "Encoding" )!= null ) encoding =header.get( "Encoding" ); if (header.get( "Content-Type" )!= null ) contentType =header.get( "Content-Type" ); } // 装填参数 if (contentType.equalsIgnoreCase( "text/html" )) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (params != null ) { for (Entry<String, String> entry : params.entrySet()) { nvps.add( new BasicNameValuePair(entry.getKey(), entry.getValue())); } } httpPost.setEntity( new UrlEncodedFormEntity(nvps, encoding)); } //JOSN格式参数 if (contentType.equalsIgnoreCase( "application/json" )) { StringEntity myEntity = new StringEntity(JSON.toJSONString(params.get( "data" )), ContentType.create( "application/json" , "UTF-8" )); httpPost.setEntity(myEntity); } System.out.println( "请求地址:" + url); // 执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost,localContext); // 获取结果实体 try { // 如果需要输出cookie if (outCookies!= null ){ List<Cookie> cookies = cookieStore.getCookies(); for ( int i = 0 ; i < cookies.size(); i++) { outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue()); } } HttpEntity entity = response.getEntity(); System.out.println( "返回:" + response.getStatusLine()); if (entity != null ) { // 按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, encoding); // System.out.println("返回:"+body); } } finally { response.close(); } } finally { client.close(); } return body; } public static void main(String[] args) throws Exception { String body =get( "https://www.baidu.com/" ); System.out.println(body); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
2014-12-08 页面静态化