安卓HTTPS请求

4

我尝试了很多选项,都快要疯了。每次尝试向URL发送请求时,我都会收到SSL异常。

在C#中使用HttpWebRequest可以完美解决这个问题。

我收到的错误信息如下:

Not trusted server certificate
java.security.cert.CertPathValidatorException: TrustAnchor for CertPath not found.

我现在正在尝试以下方法,但我已经尝试了自定义Socket工厂等所有方法。 请帮忙!
    final String httpsURL = "https://...";
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost httppost = new HttpPost(httpsURL);

    //authentication block:
    final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("mail", username));
    nvps.add(new BasicNameValuePair("password", password));
    UrlEncodedFormEntity p_entity = null;
    try {
        p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    httppost.setEntity(p_entity);

    //sending the request and retrieving the response:
    HttpResponse response = null;
    try {
        response = client.execute(httppost, _context);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    HttpEntity responseEntity = response.getEntity();

    //handling the response: responseEntity.getContent() is your InputStream
    try {
        final InputSource inputSource = new InputSource(responseEntity.getContent());
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

过去,我必须将证书添加到Java密钥库中,以使此类请求正常工作。 - mikey
@mikey,我该如何找到我传递的证书? - Benny
我不相信你通过了认证。你需要确保服务器给你的证书是可信的。C#和HttpRequest会针对不同的证书存储库验证https请求,与Java不同。这似乎是一个很好的资源:http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/。 - mikey
请注意,他提到在构建请求时创建一个证书存储文件,但我没有服务器证书。 - Benny
我自己没有做过这个。这有点取决于你是否能够获取CA证书,因为添加CA证书的证书可能更好。但是如果需要,您可以使用此工具从网站上提取证书:https://addons.mozilla.org/en-US/firefox/addon/cert-viewer-plus/ - mikey
显示剩余2条评论
1个回答

1
你需要考虑Android如何确定证书的有效性。当它需要验证证书时,它会查看签名链。如果可以在顶部找到可信的授权机构并且证书不在吊销列表中,则该证书将被信任。
为了减少耗时的查询,Android带有一份常用CA的列表,它信任这些CA。正如你在评论中指出的那样,升级后错误消失了。这很可能是因为你使用的CA被添加到了预装可信CA列表中。
如果你信任证书,你可以将其添加到这个受信任的CA列表中。此答案本问题提供了关于旧版本的详细说明!较新版本更有可能随附所需的证书。对于较新版本,你可以直接从SD卡安装证书。前往设置->安全。在凭据存储下,你会找到从设备存储安装选项。只要你使用标准格式,就应该能够安装你的证书!

我的来源:使用HTTPS和SSL实现安全 | Android开发者


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