You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 4.3及以下版本HTTP/HTTPS请求崩溃问题求助

问题分析与修复方案

先聚焦你遇到的核心错误:java.lang.IllegalStateException: Scheme 'http' not registered,这个问题的根源和修复方式我帮你梳理清楚:

问题原因

在处理HTTPS请求的分支里,你自定义了SingleClientConnManager,但只给SchemeRegistry注册了https协议的SSLSocketFactory,完全没注册http协议。

虽然当前发起的是HTTPS请求,但Apache HttpClient内部在处理一些隐性逻辑(比如潜在的重定向校验、协议兼容性检查)时,依然需要http Scheme的定义。而Android 4.3(API 18)对应的Apache HttpClient版本不会自动帮你注册这个协议,所以直接抛出了异常。

至于Android 4.4.2及更高版本能正常运行,是因为这些版本的HttpClient实现做了优化,默认已经预注册了http、https这类常用协议,不需要手动添加。

修复方案

在HTTPS分支的SchemeRegistry中,同时注册http协议即可,用PlainSocketFactory来处理HTTP请求逻辑。

修改后的HTTPS分支代码如下:

else{
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    
    // 新增:注册HTTP协议
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    
    // 原有的HTTPS注册逻辑
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    httpClient = new DefaultHttpClient(mgr, client.getParams());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    int AdFetchTimeout=Integer.parseInt(AdView.getFetchTimeout());
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, AdFetchTimeout);
    httpEntity = null;
    httpResponse = null;
}

额外提示

另外要注意,DefaultHttpClient在Android 6.0(API 23)已经被官方废弃了,推荐迁移到HttpURLConnection或者OkHttp这类更现代的网络库,能避免更多版本兼容性问题,也能获得更好的性能和维护支持。

内容的提问来源于stack exchange,提问作者Coder_07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:53:02