android如何使用https请求,【安卓】使用SSL证书进行https请求

笔记:

https,​安全的超文本传输协议,使用普通的http请求将无法成功,此时就要用到证书,将证书放至assets(可以打包时放入,也可以通过请求获取下载地址下载,视情况而定),再通过工厂set至HttpClient,以下为代码:

public class TrustAllSSLSocketFactory extends

SSLSocketFactory {

private static TrustAllSSLSocketFactory mInstance;

public TrustAllSSLSocketFactory(KeyStore truststore)

throws NoSuchAlgorithmException, KeyManagementException,

KeyStoreException, UnrecoverableKeyException {

super(truststore);

}

public static TrustAllSSLSocketFactory getDefault(Context

context) {

KeyStore keystore = null;

try {

CertificateFactory cf =

CertificateFactory.getInstance("X.509");

InputStream

in;

in =

context.getAssets().open("wassk.net.cer");

Certificate

ca = cf.generateCertificate(in);

keystore =

KeyStore.getInstance(KeyStore.getDefaultType());

keystore.load(null, null);

keystore.setCertificateEntry("ca", ca);

if (null ==

mInstance) {

mInstance = new

TrustAllSSLSocketFactory(keystore);

}

} catch (Exception e) {

}

return mInstance;

}

@Override

public Socket

createSocket() throws IOException {

return super.createSocket();

}

@Override

public Socket

createSocket(Socket socket, String host, int port, boolean

autoClose)

throws

IOException, UnknownHostException {

return super.createSocket(socket, host, port,

autoClose);

}

}

使用时:​client.setSSLSocketFactory(TrustAllSSLSocketFactory.getDefault(ApplicationContext.mContext));//增加证书

转载于:android如何使用https请求,【安卓】使用SSL证书进行https请求_Adn无解的博客-CSDN博客 

猜你喜欢

转载自blog.csdn.net/weixin_42602900/article/details/125367229