Android okhttp3.0 method of ignoring HTTPS certificate

Recently, the company's project requires that the network protocol supports HTTPS. I haven't had much contact before, so I want to summarize the relevant contents of HTTPS in Android development this time

1、 HTTPS certificate

For the concepts of HTTPS and certificate, you can search Baidu by yourself.

There are two types of certificates:

1. The certificate purchased from the certification authority (one certificate purchased by our company costs 4000 yuan, TMD. It's better to rent another server). If the server uses such a certificate, the mobile terminal can directly ignore this certificate and access it directly with HTTPS. The difference is that IOS has built-in many trusted certificates, so they don't need to do anything

2. The other is a self-made certificate. If such a certificate is used, it is not trusted and does not cost money. Therefore, we need to set this kind of certificate as a trust certificate in our code

2、 How to ignore certificates

1. If you add a certificate to the server, the URL of your network request will be changed from http: XX to HTTPS: XX. If you directly change HTTP to HTTPS without doing anything, the client will directly report an error, as shown in the figure:

If the local certificate is not found, start building an SSL to trust all certificates. Ignoring the certificate is actually the case.

2. Create a new class

Through this class, we can obtain sslsocketfactory, which is used to manage certificates and trust certificates

But one thing to note:

Then we set sslsocketfactory in okhttp, as shown in the figure:

After running, an error will still be reported, as shown in the figure:

This means that our request certificate is inconsistent with the server certificate, because we also need to configure a hostnameverifier to ignore host verification

3、 Add another method to the sslsocketclient class:

Then configure hostnameverifier in okhttp:

It is running and can be accessed normally

4、 Overall configuration

Copy the entire tool class into your project:

Then configure it in okhttp

If you use retro fit, configure okhttp in retro fit

In this way, you can ignore the HTTPS certificate and access your network normally. I, Android Xiaobai, am wrong. I hope the great God can point out and I hope you can support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>