本文主要是通过下列链接整理得到,感谢大大!
https://www.icode9.com/content-4-675617.html
在工作中需要用到用post的方式访问https,使用的函数代码如下:
// 访问url
// 成功返回0,失败返回错误码
int VisitUrl( LPCTSTR pszUrl, pcstr pszPost, std::string& strRet)
{
ASSERT( _tccmp(pszUrl, _T("http://")) == 0 || _tccmp(pszUrl, _T("https://"))==0);
strRet.clear();
CInternetSession mySession(NULL,0);
//连结超时没效果的, 发送超时与接收超时有用, 连结超时可以用多线程WaitForSingleObject来实现
mySession.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 3000); // 5000毫秒的连接超时
mySession.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 2000); // 5000毫秒的发送超时
mySession.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 2000); // 5000毫秒的接收超时
mySession.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 2000); // 5000毫秒的发送超时
mySession.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 2000); // 5000毫秒的接收超时
int ret = -1;
CHttpConnection* pConn = NULL;
CHttpFile* myHttpFile=NULL;
try
{
if ( pszPost && 0!=pszPost) {
// 解析服务器名和路径
DWORD dwServiceType = 0;
INTERNET_PORT nPort = 0;
CString strServer, strObject;
BOOL bOk = AfxParseURL(pszUrl, dwServiceType, strServer, strObject, nPort);
if ( !bOk) {
mySession.Close();
return ret;
}
if (AFX_INET_SERVICE_HTTP == dwServiceType)
{
pConn = mySession.GetHttpConnection(strServer, nPort);
myHttpFile = pConn->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
}
else if (AFX_INET_SERVICE_HTTPS == dwServiceType)
{
pConn = mySession.GetHttpConnection(strServer, INTERNET_FLAG_SECURE, nPort);
myHttpFile = pConn->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject, NULL, 1, NULL, NULL,
INTERNET_FLAG_SECURE | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD |
INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID);//SECURITY_FLAG_IGNORE_UNKNOWN_CA
} else {
// 不认识的类型不处理
mySession.Close();
return ret;
}
// 请求头
CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded");
int postLen = strlen(pszPost);
BOOL result = myHttpFile->SendRequest(strHeaders, (LPVOID)pszPost, postLen);
} else {
myHttpFile=(CHttpFile*)mySession.OpenURL( pszUrl);
}
CString strOutTxt;
// 把数据接收过来
CString myData;
if ( NULL != myHttpFile) {
while(myHttpFile->ReadString(myData)) {
strRet+=myData;
}
ret = 0;
}
}
catch(...) {
ret = GetLastError();
}
if ( pConn) {
pConn->Close();
delete pConn;
}
if ( myHttpFile) {
myHttpFile->Close();
delete (myHttpFile);
}
mySession.Close();
return ret;
}