QT5.1 调用https
以VS开发为例。因为https访问需要用到SSL认证,而QT默认是不支持SSL认证,所以在使用之前必须先做一些准备工作:
需要安装OpenSSL库:
1、首先打开http://slproweb.com/products/Win32OpenSSL.html网页;
2、下载安装包,我下载的是:Win32 OpenSSL v1.0.1c Light安装包,随着时间的推进,这个版本会不断更新的;
3、安装(exe文件)到本地,并且在安装过程中选择将库安装到OpenSSL的安装目录(/bin)下面。
4、将libeay32.dll 和 ssleay32.dll 文件拷贝到Qt中的存放有QtNetwork4.dll和QtNetworkd4.dll的文件目录下。我的是D:\Qt\4.8.2\bin
现在可以编写代码:
1 QNetworkRequest request; 2 QSslConfiguration config; 3 4 QSslConfiguration conf = request.sslConfiguration(); 5 conf.setPeerVerifyMode(QSslSocket::VerifyNone); 6 conf.setProtocol(QSsl::TlsV1SslV3); 7 request.setSslConfiguration(conf);
上面三句添回检验证书模式与协议,并设置给对应QNetworkRequest,非常重要,在这里花费了我半天的时间才找到问题
1 request.setUrl(QUrl("https://www.xxx.com/html.jsp")); 2 request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json")); 3 request.setHeader(QNetworkRequest::ContentLengthHeader, bytePost.length()); 4 QNetworkReply *pReply = pManager->post(request, bytePost);
备注:
SSL证书认证,有以下三种:
1.
1 QSslConfiguration config ; 2 3 config.setPeerVerifyMode(QSslSocket::VerifyNone); 4 config.setProtocol(QSsl::TlsV1); 5 6 QNetworkRequest request(req); 7 request.setSslConfiguration(config);
2.
1 QNetworkRequest request ; 2 3 request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true); 4 QNetworkReply* reply = QNetworkAccessManager::createRequest(op, request, outgoingData); 5 reply->ignoreSslErrors();
3.
1 QSslConfiguration config ; 2 3 QList<QSslCertificate> certs = QSslCertificate::fromPath("C:\\FiddlerRoot.crt"); 4 config.setCaCertificates(certs); 5 6 QNetworkRequest request(req); 7 request.setSslConfiguration(config);