Testing HTTPS with Android Emulator and local API server
-
wrote on 27 Nov 2022, 15:03 last edited by
I'm trying to test my API server locally with HTTPS using self signed certificates. When I try:
request.setUrl(QUrl("https://10.0.2.2:8999/test/")); nAccessMang->post(request, p.query().toUtf8());
I get the error:
"SSL handshake failed: The host name did not match any of the valid hosts for this certificate"
Noting that making an
https
get
request in a similar way works just fine:request.setUrl(QUrl("https://www.google.com")); nAccessMang->get(request);
Also,
http
works without errors when making the request to my local API server.request.setUrl(QUrl("http://10.0.2.2:8999/test/")); nAccessMang->post(request, p.query().toUtf8());
Here are the steps I took to get the above error:
- First try this on its own (just adding
https
to my request):
request.setUrl(QUrl("https://10.0.2.2:8999/test/")); ... # get and set parameters from form. nAccessMang->post(request, p.query().toUtf8());
- Figure I need to add a certificate. So I created a self signed certificate:
openssl genrsa 2048 > key.key chmod 400 key.key openssl req -new -x509 -nodes -sha256 -days 365 -key key.key -subj "/CN=localhost" -out crt.crt # I have also tried the Android Emulator's IP for the host machine as the CN: # openssl req -new -x509 -nodes -sha256 -days 365 -key key.key -subj "/CN=10.0.2.2" -out crt.crt
I have also tried using the following config when creating the certificate:
# ssl.cnf [req] req_extensions = v3_req distinguished_name = req_distinguished_name prompt = no [req_distinguished_name] C = US ST = CA L = City O = Test OU = Division CN = Test.com # tried 10.0.2.2 here as well. [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation subjectAltName = @alt_names [alt_names] DNS.1 = localhost DNS.2 = test_server IP.1 = 127.0.0.1 IP.2 = 10.0.2.2 # then openssl req -new -x509 -nodes -sha256 -days 365 -key key.key -out crt.crt -config ssl.cnf
-
Add cert to qrc file
-
Add to code
QSslConfiguration config = QSslConfiguration(); config.setProtocol(QSsl::TlsV1_2OrLater); QFile file(":/ssl/crt.crt"); file.open(QIODevice::ReadOnly); const QByteArray bytes = file.readAll(); file.close(); const QSslCertificate certificate(bytes); QList<QSslCertificate> certs(1); certs.append(certificate); config.addCaCertificates(certs); request.setSslConfiguration(config); request.setUrl(QUrl("https://10.0.2.2:8999/test/")); ... # get and set parameters from form. nAccessMang->post(request, p.query().toUtf8());
What am I missing to successfully make this
https
request to my local API server for testing? - First try this on its own (just adding
1/1