gpt4 book ai didi

java - Android HttpsUrlConnection 验证 SSL

转载 作者:行者123 更新时间:2023-11-29 22:17:56 25 4
gpt4 key购买 nike

我有一个关于在 Android 中使用 HttpsUrlConnection class 验证 SSL 的问题。我需要使用安全连接连接到网络服务器并验证 ssl。我必须检查它是否已过期,以及证书名称是否与自定义名称匹配。可选 - 如果也可以验证 SSL 证书缩略图(到预定义的缩略图),那就太好了。这是我现在用来连接服务器的代码:

public void UseHttpsConnection(String url, String charset, String query) {

try {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
}
@Override
public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };

// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance( "TLS" );
sslContext.init( null, trustAllCerts, new java.security.SecureRandom() );
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();



System.setProperty("http.keepAlive", "false");
HttpsURLConnection connection = (HttpsURLConnection) new URL(url)
.openConnection();
connection.setSSLSocketFactory( sslSocketFactory );
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException logOrIgnore) {
logOrIgnore.printStackTrace();
}
}

int status = ((HttpsURLConnection) connection).getResponseCode();
Log.i("", "Status : " + status);

for (Entry<String, List<String>> header : connection
.getHeaderFields().entrySet()) {
Log.i("Headers",
"Headers : " + header.getKey() + "="
+ header.getValue());
}

InputStream response = new BufferedInputStream(
connection.getInputStream());

int bytesRead = -1;
byte[] buffer = new byte[30 * 1024];
while ((bytesRead = response.read(buffer)) > 0) {
byte[] buffer2 = new byte[bytesRead];
System.arraycopy(buffer, 0, buffer2, 0, bytesRead);
handleDataFromSync(buffer2);
}

connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}

我在这里需要一点帮助,因为我对 SSL 验证和使用它的基本知识不熟悉。感谢您提供任何帮助!

最佳答案

如果你想验证证书,你要做的第一件事就是扔掉那个完全信任任何东西的不安全的 TrustManager。而是编写一个检查以您要求的方式收到的证书。

关于java - Android HttpsUrlConnection 验证 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8061677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com