/**
* 发起HTTP请求
*/
#define NORMAL_CONNECT INTERNET_FLAG_KEEP_CONNECTION
#define SECURE_CONNECT NORMAL_CONNECT | INTERNET_FLAG_SECURE
#define NORMAL_REQUEST INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE
#define SECURE_REQUEST NORMAL_REQUEST | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID
int HttpCall(CString Url, int RequestType, CString SendPacket, CString* RecvPacket)
{
if (Url.IsEmpty() || Url.GetLength()<=0) {
return RET_PARAMS_ERROR;
}
CInternetSession session;
CString strObject, strHost;
DWORD dwServiceType;
INTERNET_PORT nPort;
if (AfxParseURL(Url, dwServiceType, strHost, strObject, nPort)==0) {
return RET_URL_PARSE_ERROR;
}
try {
CHttpConnection* pHttp = session.GetHttpConnection(strHost, 0, nPort, NULL, NULL);
if (pHttp==NULL) {
session.Close();
return RET_HTTP_CONNECT_ERROR;
}
CHttpFile *pF = pHttp->OpenRequest(RequestType, strObject, NULL, 1, NULL, "HTTP/1.1", INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_DONT_CACHE);
if (pF==NULL) {
session.Close();
delete pHttp;
pHttp = NULL;
return RET_HTTP_REQUEST_ERROR;
}
pF->AddRequestHeaders("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
DWORD dwRet;
CString strContentLength;
int nContentLen = SendPacket.GetLength();
strContentLength.Format("Content-Length: %d", nContentLen);
pF->AddRequestHeaders(strContentLength);
pF->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)SendPacket, nContentLen);
pF->QueryInfoStatusCode(dwRet);
if (dwRet!=HTTP_STATUS_OK) {
session.Close();
delete pHttp;
pHttp = NULL;
return RET_HTTP_RESPONSE_ERROR;
}
CString strBuffer, strRead;
while(pF->ReadString(strRead)) {
strBuffer += "\r\n";
strBuffer += strRead;
}
session.Close();
pHttp->Close();
delete pHttp;
pF->Close();
delete pF;
strBuffer.TrimLeft("\r\n");
#ifdef _DEBUG
// 写原始包文
#endif
char* szGbkBuf = new char[strBuffer.GetLength()*1.5+1];
if (szGbkBuf==NULL) {
return RET_NOT_ENOUGH_MEMORY;
}
L_Utf8ToGbk((LPCTSTR)strBuffer, szGbkBuf, strBuffer.GetLength()*1.5);
*RecvPacket = szGbkBuf;
delete szGbkBuf;
return 0;
} catch(CInternetException *e) {
if (e->m_dwError==ERROR_INTERNET_TIMEOUT) {
}
} catch(CException *e) {
TCHAR szTextMsg[MAX_PATH+1];
e->GetErrorMessage(szTextMsg, MAX_PATH);
}
return RET_FUNCTION_ERROR;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)