SSL无法在android中运行

时间:2016-06-21 13:01:33

标签: android ssl https openssl httpclient

我在通过Android应用程序通过 https 协议与服务器通信时遇到问题。

我在谷歌搜索很多,但我仍然没有得到正确的解决方案。

这是我的代码

PostActivity.java:

        DefaultHttpClient client = new MyHttpClient(getApplicationContext());
        HttpPost poster = new HttpPost(GlobalUrl.EXPERT_REGISTRATION_URL); //replacing the test expert url

        File resume = new File(mFilePath);  //Actual file from the device
        MultipartEntityBuilder entity = MultipartEntityBuilder.create();
        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("fName", new StringBody("first", ContentType.MULTIPART_FORM_DATA));
        entity.addPart("attachment", new FileBody(resume));

        return client.execute(poster, new ResponseHandler<String>() {
            public String handleResponse(HttpResponse response) throws IOException {
                HttpEntity respEntity = response.getEntity();
                Log.e(TAG, "handleResponse: status line  " + response.getStatusLine());
                return EntityUtils.toString(respEntity);
            }
        });

MyHttpClient.java:

public class MyHttpClient extends DefaultHttpClient {

Context context;

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

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", getSSLSocketFactory(), 443));
    return super.createClientConnectionManager();
}
private SSLSocketFactory getSSLSocketFactory() {

    InputStream in = null;
    try {
        KeyStore localTrustStore = KeyStore.getInstance("BKS");
        in = context.getResources().openRawResource(R.raw.keystore);
        localTrustStore.load(in, context.getResources().getString(R.string.keystore_pass).toCharArray());
        return new SSLSocketFactory(localTrustStore);
    } catch (Exception e) {
        throw new RuntimeException("Could not create SSLSocketFactory", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

}

以上代码在同一域中的 http 协议中正常运行。 我检查服务器端的响应,它看起来像这样

Array([Cookie2] => $Version=1
[Cookie] => PHPSESSID=978f91620a34d22234b97fc1ba1ab4a3
[User-Agent] => Apache-HttpClient/4.5.1 (java 1.4)
[Connection] => close
[Host] => www.domain.com
)

请求的正文是空的。除标题字段外,服务器端没有收到任何内容。

我的SSL证书是自签名的。 我发现如果SSL证书是自签名的,那么我们需要创建一个Keystore来与服务器通信。 我跟着this post ,我从服务器创建了一个带有根证书的密钥库。

但仍无效。

  

我发现自签名证书不受android信任。   这是真的?如果是,那我该怎么解决呢?

任何人都可以帮我这个吗?

0 个答案:

没有答案