当我尝试调用我的Web服务时,我面临4.1及以上Android设备的问题。我已将.cer文件转换为bks并使用以下代码:
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = c.getResources().openRawResource(R.raw.test);
trusted.load(in, "password".toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
trustManagerFactory.init(trusted);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(trusted, "password".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tm, null);
URL request = new URL(URL);
urlConnection = (HttpsURLConnection) request.openConnection();
urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
urlConnection.setSSLSocketFactory(context.getSocketFactory());
urlConnection.setDoInput(true);
urlConnection.setReadTimeout(200000);
urlConnection.connect();
InputStream ina = urlConnection.getInputStream();
BasicHttpEntity res = new BasicHttpEntity();
res.setContent(ina);
HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1,
urlConnection.getResponseCode(), "");
resp.setEntity(res);
HttpEntity responseEntity = resp.getEntity();
InputStream data = responseEntity.getContent();
此代码适用于4.0及以下设备,但对于4.1,我收到“ 403 forbidden error ”。
不幸的是,我无法找到错误的地方,任何合适的帮助。
答案 0 :(得分:0)
trusted
中的内容是什么?如果您不需要客户端身份验证,则无需构建KeyManagerFactory
,只需将null
作为第一个参数传递给context.init()
。