我的网站有地址https://blablabla.com(不是实际地址)。它没有CA的批准证书。因此,访问该网站的任何用户都会获得证书异常(在浏览器上);这个例外他/她必须添加到浏览器,然后网站开始在浏览器上工作。
我有以下内容:
当服务器配置为不需要客户端证书时,客户端可以连接到服务器。连接工作正常,但我对android没有反应。
我已经写了一些API并将它们上传到服务器上。当我从手机上的移动端调用API时,我希望在移动设备上获得结果。但是,我得不到服务器的响应;我想我错过了一些东西。继承人我做了什么..请帮助我。
private static final HostnameVerifier DUMMY_VERIFIER = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
public static String method(String url)
throws Exception {
// Trust manager to accept all certificates..
TrustManager localTrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
};
HttpsURLConnection con = null;
try {
// URL object is built..
URL urlObj = new URL(url);
SSLContext sslc = SSLContext.getInstance("TLS");
sslc.init(null, new TrustManager[] { localTrustManager },
new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslc
.getSocketFactory());
// Connection is established..
con = (HttpsURLConnection) urlObj.openConnection();
con.setHostnameVerifier(DUMMY_VERIFIER);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setUseCaches(false);
con.setDoOutput(true);
DataOutputStream writer_stream = new DataOutputStream(
con.getOutputStream());
// for sending info to server..
writer_stream.writeBytes(new_request);
writer_stream.flush();
writer_stream.close();
// Get Response from the server..
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (con != null) {
con.disconnect();
}
}
}
答案 0 :(得分:0)
这是我在MainActivity的onCreate方法中所做的。
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
try {
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] tm = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
// not implemented
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
// not implemented
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}catch(Exception e){}