標籤:vat cli .net host soc https factory 解決方案 efault
我們的業務代碼裡有需要用爬蟲爬取商品的圖片地址,然後在轉到我們的伺服器裡的過程,中間當然少不了下載圖片的過程,最近目標網站有些改變,就是之前http首碼的圖片地址部分改成了https,然後就造成了一個問題,圖片下載不了,查看log,發現一個java的SSLException.
異常是: java.lang.RuntimeException:Received fatal alert: protocol_version
異常的根源是:javax.net.ssl.SSLException: Received fatal alert: protocol_version.
----------------------------------------------------------------------------------------------------------------
原因是: https的請求需要加上ssl的驗證,但是代碼裡一般只用到http,即使用到https也只是換了個首碼,並沒有帶上ssl驗證的過程。
原始碼:
private static final PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER;private static final CloseableHttpClient HTTP_CLIENT;static {HTTP_CLIENT_CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build());HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();HTTP_CLIENT = HttpClientBuilder.create().setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER).setDefaultRequestConfig(requestConfig).build();}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
+ EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
----------------------------------------------------------------------------------------------------------------
解決方案:加上SSL的驗證,加上協議
修改後可用的代碼:
private static final PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER;private static final CloseableHttpClient HTTP_CLIENT;static {SSLContext ctx = SSLContexts.createSystemDefault();SSLConnectionSocketFactory fac =new SSLConnectionSocketFactory(ctx, new String[]{"SSLv2Hello", "TLSv1.2"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);HTTP_CLIENT_CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", fac).build());HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();HTTP_CLIENT = HttpClientBuilder.create().setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER).setDefaultRequestConfig(requestConfig).build();}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
+ EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
希望能幫到你。。。
https Java SSLException protocol_version的問題解決方案