Android javax.net.ssl.SSLException: hostname in certificate didn't match...

javax.net.ssl.SSLException: hostname in certificate didn't match证书不匹配的主机名(使用的是AsyncHttpClient) 最近做项目对接https的接口,突然出现这种问题,之前还没有出现过,具体原因好像是后台设置了多个站点的原因,因为单个站点是没有问题的。具体原因没有深究。下面是我的解决方案,搜了好多,在一个博客底下的评论找到了方向,感谢。方案如下:import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.AsyncHttp... 阅读详情

最近在开发过程中,遇到一个bug,我们的App在下载一个文件的时候,服务器端返回ConnectionException:

javax.net.ssl.SSLException: hostname in certificate didn't match: <foo.net> != <bar.com> OR <bar.com> OR <www.bar.com>
我的代码很简单:

request = new HttpPost("https://foo.net/api/v1/baz");
request.setHeader("Authorization", "user:pass");
response = httpClient.execute(request);

为什么会有这个错误呢?这主要跟server 的ssl 验证方式有关。

The most likely cause for this problem is that the server uses Server Name Indication to choose which certificate to send. If the client doesn't support SNI, the server cannot choose which certificate to send during the SSL/TLS handshake (before any HTTP traffic is sent). SNI is required when you want to use multiple certificates on the same IP address and port, but not all clients support it.

 Apache HTTP Client library support SNI is quite recent, and certainly hasn't made it into the Android release.

Apache HttpClient supports SNI on Oracle’s Java 1.7 since 4.3.2, but this is not useable with Android’s Java flavour and it doesn’t seem that Google is willing to update the library. So, HttpClient doesn’t support SNI on Android by default.

两种解决方法:
1. Server 修改:to use a distinct IP address for each host (so as not to need SNI), if you're in control of server
2. 客户端修改:to use another HTTP Client library (e.g. HttpsURLConnection).  HttpsURLConnection which supports SNI by default since Android 2.3.x (see Android’s HTTP Clients).

参考:[Android] Using SNI and TLSv1.2 with Apache HttpClient library

If you want to use SSL/TLS with SNI (Server Name Indication) on Android, you’re basically encouraged to use HttpsURLConnection which supports SNI by default since Android 2.3.x (see Android’s HTTP Clients).

However, if you want to use other HTTP verbs than OPTIONS, HEAD, TRACE, GET, POST, PUT or DELETE (look for “HTTP Methods” in the docs), HttpsURLConnection is not an option. So you will have to stick with the HttpClient library, i.e. the DefaultHttpClient / AndroidHttpClient classes.

Apache HttpClient 4.0-alpha is shipped with Android, and it doesn’t seem that Google is willing to update the library. So, if you need a newer HttpClient version (and there are good reasons why you might need it), the HttpClient package names (Java name spaces) have to be changed. httpclientandroidlib is such a repackaging of recent HttpClient libraries to Android. In the meanwhile, there’s an official Android port of HttpClient.

HttpClient supports SNI on Oracle’s Java 1.7 since 4.3.2, but this is not useable with Android’s Java flavour. So, HttpClient doesn’t support SNI on Android by default.

However, there are two ways to get SNI:

  1. Since Android 4.2+ (API level 17) they have officially added SNI support to a class called SSLCertificateSocketFactory.
  2. Since Android 2.3 (Gingerbread), SNI is available in the OpenSSL implementation used by Android’s Java flavour. Sockets created by SSLCertificateSocketFactory are instances of SSLSocketImpl, and this class has a method called setHostname(String) that enables SNI and sets the SNI hostname for this socket. However, this feature is not documented and can only be used by reflection. It works on all devices I have seen, but theoretically, there might be Android variants (for instance, by certain vendors) that don’t provide this method because it’s not documented.
Using these two methods, it’s possible to add SNI support for your HttpClient application, too. (See code example below).

TLS v1.1/v1.2

Android versions >= 4.1and < 5.0 support TLS 1.1 and TLS 1.2, but these (newer and more secure) TLS versions are disabled, while only SSLv3 and TLSv1 stay enabled by default. This is fixed in Android 5.0, but for the versions between you’ll have to enable TLSv1.1 and TLSv1.2 manually:

ssl.setEnabledProtocols(ssl.getSupportedProtocols());

This line is for demonstration only! Actually, you should exclude SSLv3, too. You should also care about the used algorithms (read the NIST recommendations and other related documented) and maybe set them manually. Be sure that you know what you do, otherwise you can’t expect much security.

Working example for stock Android HttpClient

This code is for the HttpClient version which is shipped with Android (HttpClient 4.0-alpha). Look at the links below for an example using a recent HttpClient version.
// create new HTTP client
client = new ApacheHttpClient();

// use our own, SNI-capable LayeredSocketFactory for https://
SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry();
schemeRegistry.register(new Scheme("https", new TlsSniSocketFactory(), 443));
Then define your TlsSniSocketFactory:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class TlsSniSocketFactory implements LayeredSocketFactory {
    private static final String TAG = "davdroid.SNISocketFactory";

    final static HostnameVerifier hostnameVerifier = new StrictHostnameVerifier();

    // Plain TCP/IP (layer below TLS)
    @Override
    public Socket connectSocket(Socket s, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
            return null;
    }

    @Override
    public Socket createSocket() throws IOException {
            return null;
    }

    @Override
    public boolean isSecure(Socket s) throws IllegalArgumentException {
            if (s instanceof SSLSocket)
                    return ((SSLSocket)s).isConnected();
            return false;
    }

    // TLS layer
    @Override
    public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
            if (autoClose) {
                    // we don't need the plainSocket
                    plainSocket.close();
            }

            // create and connect SSL socket, but don't do hostname/certificate verification yet
            SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
            SSLSocket ssl = (SSLSocket)sslSocketFactory.createSocket(InetAddress.getByName(host), port);

            // enable TLSv1.1/1.2 if available
            // (see https://github.com/rfc2822/davdroid/issues/229)
            ssl.setEnabledProtocols(ssl.getSupportedProtocols());

            // set up SNI before the handshake
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    Log.i(TAG, "Setting SNI hostname");
                    sslSocketFactory.setHostname(ssl, host);
            } else {
                    Log.d(TAG, "No documented SNI support on Android <4.2, trying with reflection");
                    try {
                         java.lang.reflect.Method setHostnameMethod = ssl.getClass().getMethod("setHostname", String.class);
                         setHostnameMethod.invoke(ssl, host.getHostName());
                    } catch (Exception e) {
                            Log.w(TAG, "SNI not useable", e);
                    }
            }

            // verify hostname and certificate
            SSLSession session = ssl.getSession();
            if (!hostnameVerifier.verify(host, session))
                    throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);

            Log.i(TAG, "Established " + session.getProtocol() + " connection with " + session.getPeerHost() +
                            " using " + session.getCipherSuite());
            return ssl;
    }
}

Node-RED教程(二):Node-RED的面板的操作 Node-RED系列(二):Node-RED的面板的操作 要使用Node-RED去搭建一个物联网平台,链接设备,设备通信,就必须要先熟悉Node-RED的这种面板,对于一个新的项目,在动手做之前一点想对这个的技术的文档有足够的了解做起来才能游刃有余。本期我给大家介绍一下Node-RED的各种面板,熟悉这些面板后,在后续的搭建Iot服务中,会举重若轻,同时该系列的文档,难度会逐步加深,知道了本章解释的名称后对后续文章的理解有很大帮助。 面板1:默认节点选项列表 安装Node-RED后默认的节点分为这5大类 阅读详情

相关推荐

应急响应之windows日志分析工具logparser使用

windows日志分析工具logparser使用介绍

u013930899的博客 8133

javax.net.ssl.SSLException: hostname in certificate didn't match:

使用HttpClinet 遇到 javax.net.ssl.SSLException: hostname in certificate didn't match: &lt;cpd.vivo.com.cn&gt; != &lt;*.cdn.myqcloud.com&gt; OR &lt;*.cdn.myqcloud.com&gt; OR &lt;*.2144.cn&gt; OR &lt;*.214...

xcc_2269861428的博客 4349

MONAI教程<1>-安装

MONAI的安装非常简单,常用的有两种方法: 直接 pip install monai 从GitHub 上安装 monai是通常配合其他库一起使用的,比如pytorch, nibabel, skimage, pillow等等。缺什么直接pip install 就行

Tina姐的博客 1万+

报错javax.net.ssl.SSLException: hostname in certificate didn't match--validate.xxx.com.cn

解决方法: https://blog.csdn.net/shenhaiyushitiaoyu/article/details/84841360

shenhaiyushitiaoyu的博客 4万+

three.js中如何高效加载并播放GLB格式的3D动画

本文详细介绍了在three.js中高效加载并播放GLB格式3D动画的最佳实践。通过对比GLB与GLTF格式的优势,提供从环境搭建、模型加载到动画控制的完整解决方案,并分享性能优化技巧和常见问题排查方法,帮助开发者提升3D动画项目的开发效率和用户体验。

weixin_27890975的博客 364

Embarcadero Dev-C++ 6.3安装教程【保姆级】

Embarcadero Dev-C++ 6.3安装教程,保姆级教程~

Thebest_jack的博客 1万+

httpclient对象请求时报错javax.net.ssl.SSLException: hostname in certificate didn‘t match

学习httpclient对象请求时出现如下报错: 出现javax.net.ssl.sslexception报错是因为证书不匹配的主机名的问题。 可以在请求的时候多加上表示修改org.apache.http的主机名验证的代码就可以解决 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); 我的原先报错的代码如下: package com.course.httpclient.demo;

代码海中一粒米 1640

华为OD机试2025C卷 - 字符串解密 (C++ & Python & JAVA & JS & GO)

华为OD机试 2025C卷 字符串解密,提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解

qq_45776114的博客 981

hostname in certificate didn‘t match

描述 某服务商对接公司的在阿里云配置的API网关时,对方开发沟通说我们公司的HTTPS有问题,请求接口后报如下错误: javax.net.ssl.SSLException: hostname in certificate didn't match: <马赛克.com> != <*.alicloudapi.com> OR <*.alicloudapi.com> OR <alicloudapi.com> 看到错误信息,第一反应是HTTPS证书有问题,所以HTTP

祈雨v的博客 1万+

NPC 三电平逆变器中点电位平衡算法详解

最常用:零序电压注入(简单、计算量小)最可靠:虚拟空间矢量调制(VSVPWM)及其改进形式(全范围平衡)趋势:结合模型预测控制(MPC)或智能算法(模糊、神经网络)进一步提升动态性能和鲁棒性。NPC 三电平逆变器中点电位平衡算法的 C# 实现示例(零序电压注入法 + 闭环补偿)在 NPC(Neutral Point Clamped)三电平逆变器中,中点电位平衡最常用且易于软件实现的方案是零序电压注入法。

专注于前沿技术的探索与实践,热衷于从代码逻辑、架构设计到行业应用等多维度深挖技术本质。期待在技术之路上与你共同成长~ 329

LPDDR4 JEDEC标准测试实例解析--写操作

LPDDR4的JEDEC标准一致性测试项详解以及实例分享,满满干货!感兴趣的小伙伴可以持续关注!!

一只豌豆象的博客 7794

Android 链接https出现 javax.net.ssl.SSLException: hostname in certificate didn't match:

抛出的错误是这样的: javax.net.ssl.SSLException: hostname in certificate didn't match: != OR OR at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:185) at org.apache.http.conn.s

by breeze 3万+

matlab 一维相位解缠

一维相位解缠算法的matlab代码实现。

点云侠的博客 377

Android 异常:javax.net.ssl.SSLException: hostname in certificate didn't match

相关文章: Android 异常:javax.net.ssl.SSLException: hostname in certificate didn't match app用的第三方联网框架AsyncHttpClient,服务器是Https请求的,我按照以上文章的方法, 在请求之前加一句话 SSLSocketFactory.getSocketFactory().setHostnameVeri...

songzi1228的博客 414

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Android:javax.net.ssl.SSLException: hostname in certificate didn't match

问题:http请求的时候抛出 SSLException 错误 原因: 网站使用https服务器,请求的时候遇到证书验证错误。 解决:添加 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); 或者 try { httpResponse = new DefaultHttpCli...

yeliang23的博客 367

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

android网络请求忽略证书,HttpClient忽略用户证书验证的方法

程序中出了这样的异常:javax.net.ssl.SSLException: hostname in certificate didn't match。异常发生在这行代码上:httpClient.execute(httpGet);初步判断是证书的问题,准备采用忽略证书的方法解决,但在网上找了半天都没找到靠谱的代码解决,最后还是自己琢磨解决了。得到一个教训,网上找答案是不靠谱的,因为具体问题需要具体...

weixin_32893479的博客 867

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

javax.net.ssl.SSLException: hostname in certificate didn't match证书不匹配的主机名

在使用org.apache.http库请求网络时,出现javax.net.ssl.sslexception:证书不匹配的主机名 的问题 如果只是使用org.apache.http的话下面的方法就够了,在进行请求时多加一行(同时记得导入): SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVe

XiaoZhuang__的博客 3222

12. javax.net.ssl.SSLException: hostname in certificate didn't match证书不匹配的主机名

解决方法来自于: http://blog.csdn.net/trbbadboy/article/details/11562511 问题: 在使用org.apache.http库请求网络时,出现javax.net.ssl.sslexception:证书不匹配的主机名 的问题 【自己写的程序:】 【程序报的错:】 javax.net.ssl.SSLException: hostn

lemonGuo的大脑皮层、小脑、海马体、杏仁核..... 1万+

解决https,javax.net.ssl.SSLException: hostname in certificate didn‘t match 等问题

问题原因:https链接需要验证证书,证书不匹配、过期等问题导致调用接口不成功 https不校验证书,代码: static { SSLSocketFactory socketFactory = new SSLSocketFactory(getSSLContext(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry

木辰風的博客 3039

httpclient 4.2.1请求https报错 hostname in certificate didn't match 解决办法

本来直接用httpclient 4.2.1的DefaultHttpClient是可以直接请求https接口的,由于未知原因在本地请求接口一点问题都没有,放到服务器就报:javax.net.ssl.SSLException: hostname in certificate didn't match: <xxx.xxx.xx.xxx> != <*.a.xxxxx.com>,证书...

Dmowang的博客 4870

javax.net.ssl.SSLException:hostname in certificate didn't match

终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~ 现在网站用https的服务器越来越多了,在编写程序的时候往往会遇到证书验证错误。也就是SSLException错误。下面给出解决方案: private static DefaultHttpClient getHttpCl...

weixin_33739523的博客 539
上一篇: Android 如何实现应用卸载反馈,卸载监控
下一篇: Android 进程常驻、进程守护、进程保活技术的总结
苍痕
博客等级 码龄18年 241粉丝 138原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值