SSL握手异常:在Android N/7.0上握手失败。

67
我正在开发一个应用程序,(高级)用户必须设置自己的服务器(即nginx)来运行后端应用程序。相应的域名需要在应用程序中配置,以便连接。我主要在自己的手机(索尼z3c)上进行测试,并开始开发5.1版本。后来,我收到了6.0的更新,但仍然在模拟器中保持5.1的工作状态。不久前,我开始使用7.0镜像的AVD进行开发,结果让我惊讶的是它无法连接到我的服务器,告诉我SSL握手失败。我的nginx配置非常严格,但它适用于5.1和6.0,那么....?!
以下是我所知道的:
  • 我使用v24支持库,即我的compileSdkVersion为24。
  • 我使用Volley v1.0.0
  • 我尝试过TLSSocketFactory,但没有改变任何东西。它似乎大多数情况下用于防止旧的SDK版本使用SSL3。
  • 我尝试增加了timeout,但没有改变任何东西。
  • 我尝试直接使用HttpURLConnection,但除了堆栈跟踪(它没有volley引用,但是其他方面相同)之外,没有改变任何东西。

没有TLSSocketFactory,请求通过使用Volley.newRequestQueue(context)实例化的裸请求队列进行。

这是我在Android Studio中看到的:

W/System.err: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: Connection closed by peer
W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
W/System.err: Caused by: javax.net.ssl.SSLHandshakeException: Connection closed by peer
W/System.err:     at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
W/System.err:     at com.android.okhttp.Connection.connectTls(Connection.java:235)
W/System.err:     at com.android.okhttp.Connection.connectSocket(Connection.java:199)
W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:172)
W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
W/System.err:     at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:264)
W/System.err:     at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
W/System.err:     at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
W/System.err:   ... 1 more
W/System.err:   Suppressed: javax.net.ssl.SSLHandshakeException: Handshake failed
W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:429)
W/System.err:       ... 17 more
W/System.err:   Caused by: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x7ffef3748040: Failure in SSL library, usually a protocol error
W/System.err: error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE (external/boringssl/src/ssl/s3_pkt.c:610 0x7ffeda1d2240:0x00000001)
W/System.err: error:1000009a:SSL routines:OPENSSL_internal:HANDSHAKE_FAILURE_ON_CLIENT_HELLO (external/boringssl/src/ssl/s3_clnt.c:764 0x7ffee9d2b70a:0x00000000)
W/System.err:     at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
W/System.err:       ... 17 more

由于它显示“SSLV3_ALERT_HANDSHAKE_FAILURE”,我只能假设它因某种原因尝试使用SSLv3进行连接并失败,但这对我来说毫无意义。可能是密码问题,但我如何知道它正在尝试使用什么?我宁愿不在服务器上启用密码,而是进行连接尝试并重复。

我的nginx网站使用Let's Encrypt证书,并具有以下配置:

ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/ssl/certs/lets-encrypt-x1-cross-signed.pem;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:!aNULL;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ecdh_curve secp384r1;
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1.2;

我有一个脚本用来测试这些密码,并且它在服务器网络外的Wheezy VPS上确认了这些密码:

测试ECDHE-RSA-AES256-GCM-SHA384...是的 测试ECDHE-ECDSA-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试ECDHE-RSA-AES256-SHA384...否(sslv3 alert handshake failure) 测试ECDHE-ECDSA-AES256-SHA384...否(sslv3 alert handshake failure) 测试ECDHE-RSA-AES256-SHA...否(sslv3 alert handshake failure) 测试ECDHE-ECDSA-AES256-SHA...否(sslv3 alert handshake failure) 测试SRP-DSS-AES-256-CBC-SHA...否(sslv3 alert handshake failure) 测试SRP-RSA-AES-256-CBC-SHA...否(sslv3 alert handshake failure) 测试DHE-DSS-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试DHE-RSA-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试DHE-RSA-AES256-SHA256...否(sslv3 alert handshake failure) 测试DHE-DSS-AES256-SHA256...否(sslv3 alert handshake failure) 测试DHE-RSA-AES256-SHA...否(sslv3 alert handshake failure) 测试DHE-DSS-AES256-SHA...否(sslv3 alert handshake failure) 测试DHE-RSA-CAMELLIA256-SHA...否(sslv3 alert handshake failure) 测试DHE-DSS-CAMELLIA256-SHA...否(sslv3 alert handshake failure) 测试AECDH-AES256-SHA...否(sslv3 alert handshake failure) 测试SRP-AES-256-CBC-SHA...否(sslv3 alert handshake failure) 测试ADH-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试ADH-AES256-SHA256...否(sslv3 alert handshake failure) 测试ADH-AES256-SHA...否(sslv3 alert handshake failure) 测试ADH-CAMELLIA256-SHA...否(sslv3 alert handshake failure) 测试ECDH-RSA-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试ECDH-ECDSA-AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试ECDH-RSA-AES256-SHA384...否(sslv3 alert handshake failure) 测试ECDH-ECDSA-AES256-SHA384...否(sslv3 alert handshake failure) 测试ECDH-RSA-AES256-SHA...否(sslv3 alert handshake failure) 测试ECDH-ECDSA-AES256-SHA...否(sslv3 alert handshake failure) 测试AES256-GCM-SHA384...否(sslv3 alert handshake failure) 测试AES256-SHA256...否(sslv3 alert handshake failure) 测试AES256-SHA...否(sslv3 alert handshake failure) 测试CAMELLIA256-SHA...否(sslv3 alert handshake failure) 测试PSK-AES256-CBC-SHA...否(没有可用的密码) 测试ECDHE-RSA-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试ECDHE-ECDSA-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试SRP-DSS-3DES-EDE-CBC-SHA...否(sslv3 alert handshake failure) 测试SRP-RSA-3DES-EDE-CBC-SHA...否(sslv3 alert handshake failure) 测试EDH-RSA-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试EDH-DSS-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试AECDH-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试SRP-3DES-EDE-CBC-SHA...否(sslv3 alert handshake failure) 测试ADH-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试ECDH-RSA-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试ECDH-ECDSA-DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试DES-CBC3-SHA...否(sslv3 alert handshake failure) 测试PSK-3DES-EDE-CBC-SHA...否(没有可用的密码) 测试ECDHE-RSA-AES128-GCM-SHA256...是的 测试ECDHE-
我可以在模拟器的浏览器中打开服务器URL并获得完美的JSON响应,因此我知道系统本身是有能力的。所以问题是,为什么我不能在Android 7上连接?更新:我使用tcpdump和wireshark捕获了数据包,并启用了ClientHello中的密码,所以这不应该是个问题。
密码套件(18个套件)
密码套件:未知(0xcca9) 密码套件:TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256(0xc02b) 密码套件:TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384(0xc02c) 密码套件:未知(0xcca8) 密码套件:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256(0xc02f) 密码套件:TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384(0xc030) 密码套件:TLS_DHE_RSA_WITH_AES_128_GCM_SHA256(0x009e) 密码套件:TLS_DHE_RSA_WITH_AES_256_GCM_SHA384(0x009f) 密码套件:TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA(0xc009) 密码套件:TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA(0xc00a) 密码套件:TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA(0xc013) 密码套件:TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA(0xc014) 密码套件:TLS_DHE_RSA_WITH_AES_128_CBC_SHA(0x0033) 密码套件:TLS_DHE_RSA_WITH_AES_256_CBC_SHA(0x0039) 密码套件:TLS_RSA_WITH_AES_128_GCM_SHA256(0x009c) 密码套件:TLS_RSA_WITH_AES_256_GCM_SHA384(0x009d) 密码套件:TLS_RSA_WITH_AES_128_CBC_SHA(0x002f) 密码套件:TLS_RSA_WITH_AES_256_CBC_SHA(0x0035)
如您所见,0xc02f0xc030是匹配的,但下一个TLSv1.2数据包显示:Alert (21),Handshake Failure (40)

更新2:

这些是Android 5.1中ClientHello中的曲线:

椭圆曲线(25条曲线)
椭圆曲线:sect571r1(0x000e) 椭圆曲线:sect571k1(0x000d) 椭圆曲线:secp521r1(0x0019) 椭圆曲线:sect409k1(0x000b) 椭圆曲线:sect409r1(0x000c) 椭圆曲线:secp384r1(0x0018) 椭圆曲线:sect283k1(0x0009) 椭圆曲线:sect283r1(0x000a) 椭圆曲线:secp256k1(0x0016) 椭圆曲线:secp256r1(0x0017) 椭圆曲线:sect239k1(0x0008) 椭圆曲线:sect233k1(0x0006) 椭圆曲线:sect233r1(0x0007) 椭圆曲线:secp224k1(0x0014) 椭圆曲线:secp224r1(0x0015) 椭圆曲线:sect193r1(0x0004) 椭圆曲线:sect193r2(0x0005) 椭圆曲线:secp192k1(0x0012) 椭圆曲线:secp192r1(0x0013) 椭圆曲线:sect163k1(0x0001) 椭圆曲线:sect163r1(0x0002) 椭圆曲线:sect163r2(0x0003) 椭圆曲线:secp160k1(0x000f) 椭圆曲线:secp160r1(0x0010) 椭圆曲线:secp160r2(0x0011)
在ServerHello中返回了secp384r1 (0x0018)。这是来自Android 7的信息:
椭圆曲线(1个曲线)
椭圆曲线:secp256r1(0x0017)
导致握手失败。通过删除secp384r1或将其替换为默认值(prime256v1)更改nginx配置可以使其正常工作。所以问题仍然存在:我能否添加椭圆曲线?
使用模拟器和Android 7.0设备(General Mobile 4G)时,捕获的数据相同。
更新3:
小更新,但值得一提:我在使用Android 7.1.1的模拟器上使其正常工作了!它显示以下数据(再次使用tcpdump获取并使用wireshark查看):
椭圆曲线(3个曲线)
椭圆曲线:secp256r1(0x0017) 椭圆曲线:secp384r1(0x0018) 椭圆曲线:secp512r1(0x0019)
它显示相同的18个密码套件。

1
我可以在模拟器的浏览器中打开服务器URL - 最有可能的是,该浏览器没有使用Java代码进行HTTP连接,因此这只是部分测试。网络,特别是SSL处理,在Android 7.0中得到了相当大的改进,以支持网络安全配置。你是否碰巧依赖于用户证书(即通过设置添加的证书)? - CommonsWare
@Cornelis:引用我自己的话:“……和曲线”-那么曲线在哪里? - Steffen Ullrich
从配置中删除secp384r1(或将其替换为prime256v1)即可使其与secp256r1配合使用。 - Cornelis
你可以抛出 NoSuchAlgorithmException、KeyManagementException 异常。 - Mina Fawzy
刚遇到了同样的问题。是否有其他解决方案,而不是更改服务器配置? - coyer
显示剩余8条评论
9个回答

59
这是一个已知的Android 7.0回归问题,被谷歌承认并在Android 7.1.1发布之前进行了修复。这里是错误报告:https://code.google.com/p/android/issues/detail?id=224438
明确一下,这里的问题在于7.0仅支持一个椭圆曲线:prime256v1,又称secp256r1或NIST P-256,正如Cornelis在问题中指出的那样。因此,如果您的用户面临此问题,则有以下可用的解决方法(忽略您的用户理应升级到Android 7.1.1的事实):
- 配置服务器以使用prime256v1椭圆曲线。例如,在Nginx 1.10中,您可以通过设置`ssl_ecdh_curve prime256v1;`来实现。 - 如果第一种方法不起作用,请使用不依赖于椭圆曲线加密(例如DHE-RSA-AES256-GCM-SHA384)的旧密码套件(请确保您在数据安全方面知道自己在做什么)
注意:我不是椭圆曲线加密方面的专家,请务必对我的建议进行自己的研究以了解安全影响。以下是我在撰写本答案时参考的其他链接:
- https://community.letsencrypt.org/t/warning-android-7-0-clients-not-browsers-can-only-use-curve-prime256v1/23212 - https://github.com/nodejs/node/issues/1495

1
有人对上述问题有解决方案吗? - Kels
@Kels,对于这个Android 7.0的bug,目前没有真正的解决方案,只有我上面列出的解决方法。 - Vicky Chijwani
谢谢您的回复。但是当我在7.1.1中进行测试时,仍然出现了相同的错误。 - Kels
太棒了!将 ssl_ecdh_curve prime256v1; 添加到我的 /etc/nginx/snippets.d/ssl_default 中,也为我的 Matrix Synapse 服务器解决了 Riot 和 Android 7 的问题! - rubo77
2
自Nginx 1.11.0和OpenSSL 1.0.2以来,可以指定多个密码ssl_ecdh_curve prime256v1:secp384r1; - 请参阅nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_ecdh_curve。 - 4levels
@VickyChijwani 在此添加:DHE RSA GCM SHA384是一种安全的密码套件(我不知道它是否支持7.0),相对而言,它唯一的缺点是速度较慢。GCM被广泛认为比CBC更好。有人建议prime256v1存在后门,但目前没有太多其他支持。 - Antwan van Houdt

16

我曾遇到过一个使用自签名证书的问题,问题出在密码中,该密码不被Android 7.0接受。

我运行了以下命令:openssl s_client -showcerts -connect <domain>:<port>

在结果中,我发现:

Protocol : TLSv1
Cipher   : DHE-RSA-AES256-SHA

我搜索了Android版的Cipher并将其添加到了我的Retrofit Restadapter中:

ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .cipherSuites(

CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
            .build();

clientBuilder.connectionSpecs(Collections.singletonList(spec));

从这里开始,每个使用正确证书钉定或者正确证书但是使用了Android 7.0中“错误”的密码套件的连接都将被接受。

回顾这个答案已经一年了,我很高兴当时发布了它。但是,如果你有机会将证书更改为正确的加密套件,请始终选择这种方式而不是在应用程序中“降级”接受的套件。如果你必须使用自签名证书(例如嵌入式应用),那么这是一个可行的解决方案。


1
这个确切的解决方案对我们很有效 - 最近AT&T的一群Galaxy S7用户收到了7.0更新,这在一个重要事件期间完全破坏了我们的应用程序。Google太差劲了。 - DiscDev
@DiskDev,我理解的是问题在AT&T的7.0更新后仍然得到了修复,还是又出现了问题? - Wessel van Waas
1
你的解决方法为我们修复了问题。AT&T Galaxy S7用户在一两周前收到了7.0更新,由于我们不知道这个问题,导致我们的应用在使用该设备的用户中在一个非常不合时宜的时候崩溃。我们还有一个活动在一周后,有了你的解决方法(因为我们正在使用retrofit,不想对服务器端的密码进行更改),我们又恢复正常运行了。非常感谢! - DiscDev
1
谢谢,@WesselvanWaas。你救了我的一天。我无法感谢你。这是唯一有效的解决方案。 - v4_adi

14

我已经使用这种方法来解决"javax.net.ssl.SSLHandshakeException: Handshake failed"错误,并且在Android 7.0及其他版本中都可以很好地工作。

将此代码放入application类的onCreate()方法中即可。

fun initializeSSLContext(mContext: Context) {
            try {
                SSLContext.getInstance("TLSv1.2")
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
            }

            try {
                ProviderInstaller.installIfNeeded(mContext.applicationContext)
            } catch (e: GooglePlayServicesRepairableException) {
                e.printStackTrace()
            } catch (e: GooglePlayServicesNotAvailableException) {
                e.printStackTrace()
            }

        }

pls add java version as well - GeneCode
我遇到了这个错误:找不到com.google.android.gms.providerinstaller.dynamite的本地模块描述符类。 - GeneCode
这对模拟器7操作系统没有帮助。 - AlexS
1
完美地在我的三星S7上运行,你救了我的一天! - Danny Buonocore

5

在这里,我为您提供了一种关于Volley的可行解决方案:

在您创建单例代码中的队列之前:

public class VolleyServiceSingleton {

    private RequestQueue mRequestQueue;
    private HurlStack mStack;

    private VolleyServiceSingleton(){

        SSLSocketFactoryExtended factory = null;

        try {
            factory = new SSLSocketFactoryExtended();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }


        final SSLSocketFactoryExtended finalFactory = factory;
        mStack = new HurlStack() {
            @Override
            protected HttpURLConnection createConnection(URL url) throws IOException {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
                try {
                    httpsURLConnection.setSSLSocketFactory(finalFactory);
                    httpsURLConnection.setRequestProperty("charset", "utf-8");

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return httpsURLConnection;
            }

        };



        mRequestQueue = Volley.newRequestQueue(YourApplication.getContext(), mStack, -1);    

    }


}

这里介绍的是SSLSocketFactoryExtended:

public class SSLSocketFactoryExtended extends SSLSocketFactory
{
    private SSLContext mSSLContext;
    private String[] mCiphers;
    private String[] mProtocols;


    public SSLSocketFactoryExtended() throws NoSuchAlgorithmException, KeyManagementException
    {
        initSSLSocketFactoryEx(null,null,null);
    }

    public String[] getDefaultCipherSuites()
    {
        return mCiphers;
    }

    public String[] getSupportedCipherSuites()
    {
        return mCiphers;
    }

    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException
    {
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        SSLSocket ss = (SSLSocket)factory.createSocket(s, host, port, autoClose);

        ss.setEnabledProtocols(mProtocols);
        ss.setEnabledCipherSuites(mCiphers);

        return ss;
    }

    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException
    {
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        SSLSocket ss = (SSLSocket)factory.createSocket(address, port, localAddress, localPort);

        ss.setEnabledProtocols(mProtocols);
        ss.setEnabledCipherSuites(mCiphers);

        return ss;
    }

    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException
    {
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        SSLSocket ss = (SSLSocket)factory.createSocket(host, port, localHost, localPort);

        ss.setEnabledProtocols(mProtocols);
        ss.setEnabledCipherSuites(mCiphers);

        return ss;
    }

    public Socket createSocket(InetAddress host, int port) throws IOException
    {
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        SSLSocket ss = (SSLSocket)factory.createSocket(host, port);

        ss.setEnabledProtocols(mProtocols);
        ss.setEnabledCipherSuites(mCiphers);

        return ss;
    }

    public Socket createSocket(String host, int port) throws IOException
    {
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        SSLSocket ss = (SSLSocket)factory.createSocket(host, port);

        ss.setEnabledProtocols(mProtocols);
        ss.setEnabledCipherSuites(mCiphers);

        return ss;
    }

    private void initSSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random)
            throws NoSuchAlgorithmException, KeyManagementException
    {
        mSSLContext = SSLContext.getInstance("TLS");
        mSSLContext.init(km, tm, random);

        mProtocols = GetProtocolList();
        mCiphers = GetCipherList();
    }

    protected String[] GetProtocolList()
    {
        String[] protocols = { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3"};
        String[] availableProtocols = null;

        SSLSocket socket = null;

        try
        {
            SSLSocketFactory factory = mSSLContext.getSocketFactory();
            socket = (SSLSocket)factory.createSocket();

            availableProtocols = socket.getSupportedProtocols();
        }
        catch(Exception e)
        {
            return new String[]{ "TLSv1" };
        }
        finally
        {
            if(socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                }
        }

        List<String> resultList = new ArrayList<String>();
        for(int i = 0; i < protocols.length; i++)
        {
            int idx = Arrays.binarySearch(availableProtocols, protocols[i]);
            if(idx >= 0)
                resultList.add(protocols[i]);
        }

        return resultList.toArray(new String[0]);
    }

    protected String[] GetCipherList()
    {
        List<String> resultList = new ArrayList<String>();
        SSLSocketFactory factory = mSSLContext.getSocketFactory();
        for(String s : factory.getSupportedCipherSuites()){
            Log.e("CipherSuite type = ",s);
            resultList.add(s);
        }
        return resultList.toArray(new String[resultList.size()]);
    }

}

在这些代码中,我简单地添加了设备支持的所有加密方式,这对于我有效,也许能帮助别人。干杯!
顺便说一句,在清单中不需要添加安全网络配置参数。

2

我在这个问题上花了4天时间,尝试了各种方法,我的问题是使用LetsEncrypt(例如certbot)生成证书。

当我切换到另一个CA时,Android 7.0的请求开始进入。


2
默认情况下,所有应用程序使用安全连接(如TLS和HTTPS)都信任预安装的系统CA,而针对Android 6.0(API级别23)及以下版本的应用程序也默认信任用户添加的CA存储。这意味着在Android Nougat(7.0)上,CA的游戏完全改变了。如果您有密钥证书,可以添加网络安全配置文件(如果您有证书),方法如下: https://developer.android.com/training/articles/security-config.html 或者您可以创建自己的TrustManager,方法如下: https://developer.android.com/training/articles/security-ssl.html#SelfSigned 或者您可以启用您的服务器需要但在Android N上默认未启用的密码套件。例如,以下是我需要添加到自己的应用程序中以与旧的Windows CE服务器通信的两个密码套件:
    SSLSocket sslsock = (SSLSocket) createSocket();
    List<String> cipherSuitesToEnable = new ArrayList<>();
    cipherSuitesToEnable.add("SSL_RSA_WITH_RC4_128_SHA");
    cipherSuitesToEnable.add("SSL_RSA_WITH_3DES_EDE_CBC_SHA");
    sslsock.setEnabledCipherSuites(cipherSuitesToEnable.toArray(new String[cipherSuitesToEnable.size()]));

@Cornelis,很简单,因为您访问的服务器不支持Android N支持的相同密码套件。您可以使用Wireshark查看应用程序从服务器请求的确切密码套件。 - IgorGanapolsky
1
遇到了相同的问题。Android < 7 可以访问服务器,而 Android 7 在握手异常时失败。因此,这一定是 Android 7 中的一个错误。 - coyer
1
服务器配置中的密码支持开箱即用,详见官方文档。我已经通过wireshark验证了这一点(你可以在我的问题中找到ClientHello)。我还通过getSupportedCipherSuitesgetEnabledCipherSuites的输出进行了确认。至于曲线,我还没有找到一种方法来完成所有这些。 - Cornelis
@jmc34 很遗憾,这个问题仍然是一个未解决的问题。 - Cornelis
1
手动添加所需的密码套件解决了我的问题 - 谢谢 - Dean Wild
显示剩余4条评论

1
使用 OkHttp 时,您可以使用 Conscrypt,它支持此安全提供程序的开箱即用。
只需使用 Security.insertProviderAt(Conscrypt.newProvider(), 1) 进行安装,就可以使用它了!

那是唯一对我有效的解决方案,谢谢 :) - Dziki Arbuz
这个不起作用 :( - AlexS

1

我也有同样的问题。我的Nginx服务器使用sll_ecdh_curve prime384v1设置。不幸的是,后端开发人员由于客户的安全策略,不允许我按照Vicky Chijwani的指示配置Nginx服务器。我尝试使用Valley和最新版本的OkHttp库,但没有帮助。为了绕过这个bug,在Android 7.0设备上,我不得不使用WebView与API服务通信。这是我的Adapter类。我希望其他人会发现它有用。

/**
* Connection to API service using WebView (for Android 7.0 devices)
*
* Created by fishbone on 09.08.17.
*/
@RequiresApi(api = Build.VERSION_CODES.N)
class WebViewHttpsConnection extends ApiConnection {

    private static final long TIMEOUT = 30000;
    private static final String POST_DATA_SCRIPT = "javascript:(function (){" +
            "var xhr = new XMLHttpRequest();\n" +
            "xhr.open(\"POST\", \"%1$s\", true);\n" +
            "xhr.setRequestHeader(\"Content-type\", \"application/json\");\n" +
            "xhr.onreadystatechange = function () {\n" +
            "    if (xhr.readyState === 4) {\n" +
            "        listener.onResult(xhr.status, xhr.responseText);\n" +
            "    }\n" +
            "};\n" +
            "xhr.send('%2$s');\n" +
            "})();";

    WebViewHttpsConnection(Context context) {
        super(context);
    }
    /**
     *  Send data to API Service.
     *
     * @param url URL of API Service
     * @param request JSON Object serialized into String
     * @return API response
     * @throws IOException errors
     */
    @Override
    public String sendData(final URL url, final String request) throws IOException {
        // We should escape backslashes in JSON because JS unescape it back
        final String javaScript = String.format(POST_DATA_SCRIPT, url.toString(),
                request.replace("\\", "\\\\"));
        final RequestResultListener listener = new RequestResultListener();
        // We must use WebView only from 'main' Thread, therefore I using Handler with Application context
        Handler handler = new Handler(getContext().getApplicationContext().getMainLooper());
        handler.post(new Runnable() {

            @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"}) // JavaScript is only for me and I'll use it only on Android 7.0 devices, so not scary
            @Override
            public void run() {
                // WebView must be created, configured and called from the same Thread
                final WebView webView = new WebView(getContext(), null);
                webView.getSettings().setJavaScriptEnabled(true);
                webView.addJavascriptInterface(listener, "listener");
                webView.setWebViewClient(new WebViewClient() {

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        // As soon as loaded any page from target domain, we call JS-script that will make POST request
                        webView.loadUrl(javaScript);
                    }
                });
                // I cant use postUrl() method because WebView doesn't allow to define 'Content-type' header, but my API service accepts only 'application/json' content type
                // To complete CORS requirements we make any GET request to lets WebView navigate to the target domain, otherwise it will send 'null' as 'Origin' in headers
                webView.loadUrl(url.toString());
            }
        });
        // And further we waiting for response of API service
        try {
            if (!listener.latch.await(TIMEOUT, TimeUnit.MILLISECONDS)) {
                throw new IOException("Timeout connection to server");
            }
        } catch (InterruptedException e) {
            throw new IOException("Connection to server was interrupted");
        }
        if (listener.code != HttpURLConnection.HTTP_OK) {
            throw new HttpRetryException("Server return error code " + listener.code,
                    listener.code);
        }
        if (TextUtils.isEmpty(listener.result)) {
            throw new HttpRetryException("Service return empty response", listener.code);
        }
        return listener.result;
    }
    /**
     * Callback interface for receiving API Service response from JavaScript inside WebView
     */
    private static class RequestResultListener {

        CountDownLatch latch = new CountDownLatch(1);
        String result = null;
        int code;

        @JavascriptInterface
        public void onResult(int code, String result) {
            this.result = result;
            this.code = code;
            latch.countDown();
        }
    }
}

0

最终我不得不实现与 Nikolay 相似的解决方案,因为其他解决方案都没有解决问题(虽然管理员尝试修复问题而不影响安全,但我无法访问 API 服务器)。

我将我的解决方案编写为一个类,您只需将其插入到您的应用程序中即可,如下所示:

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BackupAPIService
{
    private static final String TAG = "BackupAPIService";
    private static BackupAPIService sService = null;

    // A context is required in order to run the webview.
    private Context mContext;
    // Headers for the request are stored here - they can be set, added to and removed from.
    private HashMap<String, String> mHeaders = new HashMap<>();
    // This sets the current location of the webview - it is probably best. although generally unnecessary to set this to the main page of the API.
    // However not setting it at all will throw 'no access-control-allow-origin header is present' errors.
    private String mOriginURL = "";
    // Setting a base url to the domain of the API means that any requests don't need to include this beginning of the url,
    // This must remain the same for all requests.
    private String mBaseURL = "";

    public static final int GET = 0, POST = 1;

    // NOTE
    // Please note that a singleton pattern has been used, assuming all calls are made to the same API.
    // If you are using several APIs, you may wish to modify this service to give a separate BackupAPIService object for each.
    // If you are using an unknown number of APIs, you may wish to make the constructor public and remove the static methods.
    // The datatype returned by the API is assumed to be in JSON format - if you wish to change this, you will need to manually edit line 9 of the ajaxRequest String in the GenerateRequest method.


    /**
     * This returns the created BackupAPIService if it exists, and creates a new one otherwise. However the new one will need to be set up.
     * @param context is the context in which to create the WebView. This can include the context from a service.
     * @return the current instance of the BackupAPIService if it exists, otherwise it creates a new one.
     */

    public static BackupAPIService getService(Context context)
    {
        if(sService == null)
        {
            sService = new BackupAPIService(context);
        }
        return sService;
    }

    /**
     * This allows the headers to be set for this instance of the BackupAPIService.
     * @param context is the context in which to create the WebView. This can include the context from a service.
     * @param headers are the custom headers to be sent with this request. If these already exist in the service, they will be updated. Otherwise they will be added onto the list. Please note that String headers and values should be surrounded by single quotes, ie. 'header'. To reset the headers run ResetService.
     * @return the current instance of the BackupAPIService if it exists, otherwise it creates a new one.
     */

    public static BackupAPIService getService(Context context, HashMap<String, String> headers)
    {
        return getService(context).addHeaders(headers);
    }

    /**
     * This allows the headers and the originURL to be set for this instance of the BackupAPIService.
     * @param context is the context in which to create the WebView. This can include the context from a service.
     * @param headers are the custom headers to be sent with this request. If these already exist in the service, they will be updated. Otherwise they will be added onto the list. Please note that String headers and values should be surrounded by single quotes, ie. 'header'. To reset the headers run ResetService.
     * @param originURL is the URL from which the WebView will make its requests. This should be set, as the API will throw a 'no access-control-allow-origin header is present' error otherwise.
     * @return the current instance of the BackupAPIService if it exists, otherwise it creates a new one.
     */

    public static BackupAPIService getService(Context context, HashMap<String, String> headers, String originURL)
    {
        return getService(context).addHeaders(headers).addOriginURL(originURL);
    }

    /**
     * This allows the headers and the originURL to be set for this instance of the BackupAPIService.
     * @param context is the context in which to create the WebView. This can include the context from a service.
     * @param headers are the custom headers to be sent with this request. If these already exist in the service, they will be updated. Otherwise they will be added onto the list. Please note that String headers and values should be surrounded by single quotes, ie. 'header'. To reset the headers run ResetService.
     * @param originURL is the URL from which the WebView will make its requests. This should be set, as the API will throw a 'no access-control-allow-origin header is present' error otherwise.
     * @param baseURL is the part of the API URL that never changes. This will allow you to only pass in the different URL endings as required, saving a lot of writing.
     * @return the current instance of the BackupAPIService if it exists, otherwise it creates a new one.
     */

    public static BackupAPIService getService(Context context, HashMap<String, String> headers, String originURL, String baseURL)
    {
        return getService(context).addHeaders(headers).addOriginURL(originURL).addBaseURL(baseURL);
    }

    /**
     * This resets all of the parameters of the service to their defaults as desired.
     * @param resetHeaders clears the headers if set to true.
     * @param resetBaseURL clears the baseURL if set to true.
     * @param resetOriginURL clears the originURL if set to true.
     */

    public static void ResetService(boolean resetHeaders, boolean resetBaseURL, boolean resetOriginURL)
    {
        if(sService != null)
        {
            if(resetHeaders) sService.mHeaders = new HashMap<>();
            if(resetBaseURL) sService.mBaseURL = "";
            if(resetOriginURL) sService.mOriginURL = "";
        }
    }

    /**
     * This is the basic constructor for the API.
     * @param context is the context in which to create the WebView. This can include the context from a service.
     */

    private BackupAPIService(Context context)
    {
        this.mContext = context;
    }

    /**
     * This allows the headers to be updated with the headers in the object that is sent. Existing headers in the list will be updated with their new values, and new headers will be added. Please note that String headers and values should be surrounded by single quotes, ie. 'header'. This can be done programmatically using the getCompatibleString method.
     * @param headers are the headers being added.
     * @return the current BackupAPIService object.
     */

    public BackupAPIService addHeaders(HashMap<String, String> headers)
    {
        this.mHeaders.putAll(headers);
        return this;
    }

    /**
     * This allows a single header to be added if it does not exist, or updated if it does.
     * @param key is the name of the header. Please note that String headers and values should be surrounded by single quotes, ie. 'header'.
     * @param value is the value of the header as a String.
     * @return the current BackupAPIService object.
     */

    public BackupAPIService addHeader(String key, String value)
    {
        this.mHeaders.put(key, value);
        return this;
    }

    /**
     * This allows a single header to be removed if it exists in the service
     * @param key is the name of the header
     * @return the current BackupAPIService object
     */

    public BackupAPIService removeHeader(String key)
    {
        this.mHeaders.remove(key);
        return this;
    }

    /**
     * This returns whether a variable with a given name exists in the Service
     * @param key is the name of the header
     * @return the current BackupAPIService object
     */

    public boolean getHeaderExists(String key)
    {
        return mHeaders.containsKey(key);
    }

    /**
     * This sets the originURL, which tells the API which website the request is coming from. If this is not set, the request is likely to be blocked.
     * @param originURL is the URL stating which website the request is coming from: you may wish to set this to the main website address of your API.
     * @return the current BackupAPIService object
     */

    public BackupAPIService addOriginURL(String originURL)
    {
        mOriginURL = originURL;
        return this;
    }

    /**
     * This sets the baseURL. If there is a common URL beginning for all your API calls, you can set it here and the just send the rest of the address in your calls to the Post or Get methods.
     * @param baseURL will be added onto the beginning of all of the API URL requests, allowing you to avoid having to write this each time, and send shorter requests.
     * @return the current BackupAPIService object
     */

    public BackupAPIService addBaseURL(String baseURL)
    {
        mBaseURL = baseURL;
        return this;
    }

    /**
     * This allows a post request to be sent, with the parameters as a hashmap. Please note that String parameters should take the format String param = "'{param}'", so that ajax recognises the String as a String - the getCompatibleString method can be used to automatically adds these single quotes to a given String.
     * @param URL is the url of the request - this could just be the second half of the url, if the first half has been set as the baseURL.
     * @param parameters is a hashmap of the parameters.
     * @param ajaxHandler allows you to define your own custom response with the returned information.
     */

    public void Post(String URL, HashMap<String, String> parameters, AjaxHandler ajaxHandler)
    {
        Launch(POST, URL, ajaxHandler, parameters);
    }

    /**
     * This allows a get request to be sent.
     * @param URL is the url of the request - this could just be the second half of the url, if the first half has been set as the baseURL.
     * @param ajaxHandler allows you to define your own custom response with the returned information.
     */

    public void Get(String URL, AjaxHandler ajaxHandler)
    {
        Launch(GET, URL, ajaxHandler);
    }

    /**
     * This is used by the public Post and Get methods to launch a request.
     * @param launchType is defined as either post or get by the POST and GET static constants.
     * @param URL is the url of the request - this could just be the second half of the url, if the first half has been set as the baseURL.
     * @param ajaxHandler allows you to define your own custom response with the returned information.
     * @param parameters is an optional hashmap of the parameters for a post request.
     */

    private void Launch(final int launchType, final String URL, final AjaxHandler ajaxHandler, final  HashMap<String, String>  ... parameters)
    {
        // This piece of code is required in order to allow the WebView to run from a service without throwing errors
        Handler handler = new Handler(Looper.getMainLooper());
        try
        {
            handler.post(
                    new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            GenerateRequest(launchType, URL, ajaxHandler, parameters);
                        }
                    });
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * This method generates the actual request.
     * @param launchType is defined as either post or get by the POST and GET static constants.
     * @param URL is the url of the request - this could just be the second half of the url, if the first half has been set as the baseURL.
     * @param ajaxHandler allows you to define your own custom response with the returned information.
     * @param parameters is an optional hashmap of the parameters for a post request.
     */

    private void GenerateRequest(int launchType, String URL, AjaxHandler ajaxHandler, HashMap<String, String> ... parameters)
    {
        String importAjax = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>";
        String customiseAjaxHeaders = "$.ajaxSetup({headers: { ";
        for (Map.Entry<String, String> entry : mHeaders.entrySet())
        {
            customiseAjaxHeaders += entry.getKey() + ": " + entry.getValue() + ", ";
        }
        customiseAjaxHeaders = customiseAjaxHeaders.substring(0, customiseAjaxHeaders.length()-2) + "}});";
        String postParameters = "";
        if(parameters.length>0)
        {
            for (Map.Entry<String, String> entry : parameters[0].entrySet())
            {
                postParameters += entry.getKey() + ": " + entry.getValue() + ", ";
            }
            postParameters = postParameters.substring(0, postParameters.length()-2);
        }
        //String origin = "'app.cleopatra.im'";
        String requestAddress = "'"+mBaseURL + URL + "'";
        String requestType = "Get";
        if(launchType == POST) requestType = "Post";
        String ajaxRequest = customiseAjaxHeaders + " var saveData = " +
                "$.ajax" +
                "(" +
                    "{" +
                        "type: '" + requestType + "'," +
                        "url: " + requestAddress + ", " +
                        "data: " +
                        "{" + postParameters + "}," +
                        "dataType: 'json'," +
                        "success: function(data)" +
                        "{" +
                            "ajaxHandler.handleResults(JSON.stringify(data));" + // This runs the ajax handler created below when the handler successfully returns data
                        "}," +
                        "error:function(request, status)" +
                        "{" +
                            "ajaxHandler.handleFailure('Request Failed: ' + JSON.stringify(request) + ' due to: ' + JSON.stringify(status));" + // This runs the ajax handler created below when the handler unsuccessfully returns data
                        "}" +
                    "}" +
                ");";

        CreateRequestThroughWebView(importAjax, ajaxRequest, ajaxHandler);
    }

    /**
     * This is used to create the generated request through a webview object
     * @param content is the html content of the webview - in this implementation it is currently just an import script for JQuery
     * @param request is the Ajax request script to be run on the webview
     * @param ajaxHandler allows you to define your own custom response with the returned information.
     */

    private void CreateRequestThroughWebView(String content, final String request, AjaxHandler ajaxHandler)
    {
        Log.i(TAG, "Content: " + content + "\nRequest: " + request);
        HashMap<String, String> headers = new HashMap<>();
        // create the new webview - this can run invisibly
        WebView webView = new WebView(mContext);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        // This creates a webpage at the expected location, which can be accept AJAX commands
        webView.loadDataWithBaseURL(mOriginURL, content, "text/html; charset=utf-8", "utf-8", mOriginURL);
        // Allow JavaScript to run on the page
        webView.getSettings().setJavaScriptEnabled(true);
        // Add a JavaScript interface allowing completed AJAX requests to run Java methods
        webView.addJavascriptInterface(ajaxHandler, "ajaxHandler");

        // override onPageFinished method of WebViewClient to handle AJAX calls
        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                // Run the JavaScript command once the page has loaded
                view.evaluateJavascript(request, new ValueCallback<String>()
                {
                    @Override
                    public void onReceiveValue(String s)
                    {
                        Log.i(TAG, "Request Completed: " + s);
                    }
                });
            }
        });
    }

    /**
     * This adds additional single quotes to enclose a string representing a header name, header value, variable name or variable value, so it is still recognised as a String when it is passed into Ajax.
     * @param string is the header name, header value, variable name or variable value to be modified.
     * @return an ajax compatible String.
     */

    public static String getCompatibleString(String string)
    {
        return "'" + string + "'";
    }

    /**
     * This adds additional single quotes to enclose two strings representing either a String header name and its value, or posted variable name and its value, so that they are both still recognised as Strings when they are passed into Ajax.
     * @param name is the header or variable name, header value, variable name or variable value to be modified.
     * @param value is the header or variable value to be modified.
     * @return an ajax compatible HashMap which can also be added into any existing HashMaps as necessary.
     */

    public static HashMap<String, String> getCompatibleHashMapEntry(String name, String value)
    {
        HashMap<String, String> result = new HashMap<String, String>();
        result.put(getCompatibleString(name), getCompatibleString(value));
        return result;
    }

    /**
     * This adds additional single quotes to enclose an arbitrary number of two string arrays, each representing String header name and its value, or a posted variable name and its value so that they are both still recognised as Strings when they are passed into Ajax. This is returned as a hashmap ready to be set as the necessary headers or variables for the request.
     * @param nameValuePairs is the header or variable name, header value, variable name or variable value to be modified.
     * @return an ajax compatible HashMapEntry.
     */

    public static HashMap<String, String> getCompatibleHashMap(String[] ... nameValuePairs)
    {
        HashMap<String, String> results = new HashMap<>();
        for (String[] nameValuePair: nameValuePairs)
        {
            results.put(getCompatibleString(nameValuePair[0]), getCompatibleString(nameValuePair[1]));
        }
        return results;
    }



    /**
     * This deals with the results of the Ajax API request.
     * The handleResults method of this abstracted Ajax Javascript Interface should be implemented in order to define your app's behaviour when the request completes.
     * The ConvertResultToObject method can also be used within the handleResults method in order to convert the received json string into the corresponding class.
     * The handleFailure method is called if the Ajax request fails.
     */

    public abstract static class AjaxHandler
    {
        private static final String TAG = "ajaxHandler";
        private final Context context;

        public AjaxHandler(Context context)
        {
            this.context = context;
        }

        /**
         * Overwrite this method to handle the response to your request
         * @param results is a String representation of the result from the WebView Query
         */

        @android.webkit.JavascriptInterface
        public abstract void handleResults(String results);

        /**
         * Overwrite this method to handle any failed requests
         * @param message is a String representation of the failure message from the WebView Query
         */


        @android.webkit.JavascriptInterface
        public abstract void handleFailure(String message);

        /**
         * This should generate a predefined class object from a JSON response. It was not used in the final implementation, so it has not been tested and may need tweaking
         * @param json is the json representation of the class
         * @param classOfT is the class of the object to be populated
         * @return an object of class T created from the JSON string
         */

        public <T> T ConvertResultToObject(String json, Class<T> classOfT)
        {
            Gson gson = new Gson();
            return gson.fromJson(json, classOfT);
        }
    }
}

一个示例实现如下:

// Example Ajax Implementation


// Setup basic variables


// Set up context
Context context = this.context;
// Set the beginning of the URL which is the same for all API requests
String API_URL = "https://mywebsite.com/myapi/";
// Set up the url from which requests should originate
String BASE_URL = "www.mywebsite.com";

// Set up variables to pass into the requests
// Header names and values
String API_KEY_NAME = "{API_KEY_NAME}";
String API_KEY_VALUE = "{API_KEY_VALUE}";
// Parameter names and values
String USER_NAME = "User";
String USER_VALUE = "{User name}";
String PASSWORD_NAME = "Password";
String PASSWORD_VALUE = "{User Password}";
String USER_ID_NAME = "User_id";
int USER_ID_VALUE = 7;
// Note that Strings need an extra set of single quotes to be recognised as a String when passed into Ajax. Methods have been provided which do that.
// Get the headers as a HashMap, and convert both name and value to an Ajax compatible String
HashMap<String, String> headers = BackupAPIService.getCompatibleHashMapEntry(API_KEY_NAME, API_KEY_VALUE);
// Get the parameters as a HashMap, and convert the appropriate names and values to Ajax compatible Strings
HashMap<String, String> parameters = BackupAPIService.getCompatibleHashMap(new String[] {USER_NAME, USER_VALUE}, new String[] {PASSWORD_NAME, PASSWORD_VALUE});
// Add the parameters where the values are not Strings
parameters.put(BackupAPIService.getCompatibleString(USER_ID_NAME), USER_ID_VALUE+"");
// Create or get service
BackupAPIService backupService = BackupAPIService.getService(context, headers, BASE_URL, API_URL);
// Post a request with the necessary addition to the API url set earlier for this request, the parameters set above, and an implementation of AjaxHandler which handles the results and failures as you desire
backupService.Post("user", parameters, new BackupAPIService.AjaxHandler(context){
    @Override
    public void handleResults(String results)
    {
        Log.e(TAG, "Success!! " + results);
    }

    @Override
    public void handleFailure(String message)
    {
        Log.e(TAG, "Failure :( " + message);
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接