当前位置:   article > 正文

HttpClient详解及如何设置忽略SSL_httpclient 忽略ssl

httpclient 忽略ssl

一、简介

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5.x

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.6</version>
  5. </dependency>

二、基本功能

  1. 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  2. 支持自动转向
  3. 支持 HTTPS 协议
  4. 支持代理服务器
  • 2.1 GET方法
  1. /**
  2. * 发送 get请求
  3. */
  4. public void get() {
  5. CloseableHttpClient httpclient = HttpClients.createDefault();
  6. try {
  7. // 创建httpget.
  8. HttpGet httpget = new HttpGet("http://www.baidu.com/");
  9. System.out.println("executing request " + httpget.getURI());
  10. // 执行get请求.
  11. CloseableHttpResponse response = httpclient.execute(httpget);
  12. try {
  13. // 获取响应实体
  14. HttpEntity entity = response.getEntity();
  15. System.out.println("--------------------------------------");
  16. // 打印响应状态
  17. System.out.println(response.getStatusLine());
  18. if (entity != null) {
  19. // 打印响应内容长度
  20. System.out.println("Response content length: " + entity.getContentLength());
  21. // 打印响应内容
  22. System.out.println("Response content: " + EntityUtils.toString(entity));
  23. }
  24. System.out.println("------------------------------------");
  25. } finally {
  26. response.close();
  27. }
  28. } catch (ClientProtocolException e) {
  29. e.printStackTrace();
  30. } catch (ParseException e) {
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } finally {
  35. // 关闭连接,释放资源
  36. try {
  37. httpclient.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  • 2.2 POST方法
  1. /**
  2. * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
  3. */
  4. public void post() {
  5. // 创建默认的httpClient实例.
  6. CloseableHttpClient httpclient = HttpClients.createDefault();
  7. // 创建httppost
  8. HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");
  9. // 创建参数队列
  10. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  11. formparams.add(new BasicNameValuePair("type", "house"));
  12. UrlEncodedFormEntity uefEntity;
  13. try {
  14. uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
  15. httppost.setEntity(uefEntity);
  16. System.out.println("executing request " + httppost.getURI());
  17. CloseableHttpResponse response = httpclient.execute(httppost);
  18. try {
  19. HttpEntity entity = response.getEntity();
  20. if (entity != null) {
  21. System.out.println("--------------------------------------");
  22. System.out.println("Response content: " + ntityUtils.toString(entity, "UTF-8"));
  23. System.out.println("--------------------------------------");
  24. }
  25. } finally {
  26. response.close();
  27. }
  28. } catch (ClientProtocolException e) {
  29. e.printStackTrace();
  30. } catch (UnsupportedEncodingException e1) {
  31. e1.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } finally {
  35. // 关闭连接,释放资源
  36. try {
  37. httpclient.close();
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }

 

参考资料:

 https://www.kancloud.cn/longxuan/httpclient-arron/117499                                                         https://blog.csdn.net/xiaoxian8023                                                               https://blog.csdn.net/w372426096/article/details/82713315

三、常见问题之一:如何设置忽略SSL

有时我们需要访问一些采用Https安全协议的网站,我们可以定制SSL/TLS的方式来访问该网站,HttpClient是支持的。定制SSL/TLS下节记录。采用定制SSL/TLS的方式需要导出对应网站的证书,证书还有可能过期,需要重新导入,这时可以采用绕过证书的方式。当然,有的网站是Https但是浏览器还是显示不安全,就没办法导出证书,比如12306。

解决常见报错:

方式一:

  1. HttpHost proxy = new HttpHost("10.31.16.216",18103);
  2. CloseableHttpClient httpClient = HttpClients.custom()
  3. .setProxy(proxy)
  4. .setHostnameVerifier(new AllowAllHostnameVerifier())
  5. .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
  6. {
  7. public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
  8. {
  9. return true;
  10. }
  11. }).build()).build();
  12. HttpURLConnection configurator =new HttpURLConnection(null) {
  13. @Override
  14. public void connect() throws IOException {
  15. // TODO Auto-generated method stub
  16. }
  17. @Override
  18. public boolean usingProxy() {
  19. // TODO Auto-generated method stub
  20. return false;
  21. }
  22. @Override
  23. public void disconnect() {
  24. // TODO Auto-generated method stub
  25. }
  26. };
  27. @PostConstruct
  28. public void init() throws Exception{
  29. RequestConfig httpConfig=RequestConfig.custom()
  30. .setExpectContinueEnabled(false)
  31. .setConnectionRequestTimeout(Integer.valueOf("configurator.getTransportConfig().getConnectionTimeout()"))
  32. .setConnectTimeout(Integer.valueOf("configurator.getTransportConfig().getConnectionTimeout()"))
  33. .setSocketTimeout(Integer.valueOf("configurator.getTransportConfig().getsocketTimeout()"))
  34. .build();
  35. SSLContext sslContextIgnore=SSLContexts.custom().loadTrustMaterial((cert,para)->true).build();
  36. //SSLContext sslContextIgnore=SSLContexts.custom().build();
  37. SSLConnectionSocketFactory socketFactoryIgnore=new SSLConnectionSocketFactory(sslContextIgnore,NoopHostnameVerifier.INSTANCE);
  38. HttpClient httpClient= HttpClients.custom()
  39. .setDefaultRequestConfig(httpConfig)
  40. .setMaxConnPerRoute(Integer.valueOf("configurator.getTransportConfig().getPoolMmaxSizePerRoute()"))
  41. .setSSLContext(sslContextIgnore)
  42. .setSSLSocketFactory(socketFactoryIgnore)
  43. .build();
  44. }
  45. }

方式二:

  1. SSLContextBuilder builder = new SSLContextBuilder();
  2. builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
  3. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  4. builder.build());
  5. CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
  6. sslsf).build();
  7. HttpGet httpGet = new HttpGet("https://www.baidu.com");
  8. CloseableHttpResponse response = httpclient.execute(httpGet);
  9. try {
  10. System.out.println(response.getStatusLine());
  11. HttpEntity entity = response.getEntity();
  12. EntityUtils.consume(entity);
  13. }
  14. finally {
  15. response.close();
  16. }

方式三:

  1. SSLContextBuilder builder = SSLContexts.custom();
  2. builder.loadTrustMaterial(null, new TrustStrategy() {
  3. @Override
  4. public boolean isTrusted(X509Certificate[] chain, String authType)
  5. throws CertificateException {
  6. return true;
  7. }
  8. });
  9. SSLContext sslContext = builder.build();
  10. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  11. sslContext, new X509HostnameVerifier() {
  12. @Override
  13. public void verify(String host, SSLSocket ssl)
  14. throws IOException {
  15. }
  16. @Override
  17. public void verify(String host, X509Certificate cert)
  18. throws SSLException {
  19. }
  20. @Override
  21. public void verify(String host, String[] cns,
  22. String[] subjectAlts) throws SSLException {
  23. }
  24. @Override
  25. public boolean verify(String s, SSLSession sslSession) {
  26. return true;
  27. }
  28. });
  29. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
  30. .<ConnectionSocketFactory> create().register("https", sslsf)
  31. .build();
  32. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
  33. socketFactoryRegistry);
  34. CloseableHttpClient httpclient = HttpClients.custom()
  35. .setConnectionManager(cm).build();

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/451284
推荐阅读
  

闽ICP备14008679号