bool PostData(CString strUrl, CString strPara, std::string &strReturnValue)
{
bool bRet = false;
CString strServer, strObject, strHeader, strRet;
unsigned short nPort;
DWORD dwServiceType;
if(!AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort))//不是有效有网络地址!
return false;
CInternetSession sess;//Create session
CHttpFile* pFile = NULL;
CHttpConnection *pServer = sess.GetHttpConnection(strServer, nPort);
if(pServer == NULL)//连接服务器失败!
return false;
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,strObject,NULL,1,NULL,NULL,INTERNET_FLAG_EXISTING_CONNECT);
if(pFile == NULL)//找不到网络地址
return false;
pFile->AddRequestHeaders(_T("Content-Type: application/x-www-form-urlencoded"));
pFile->AddRequestHeaders(_T("Accept: */*"));
//将宽字符strPara 转换为窄字符后再SendRequest,很重要!!!
int ansiLen = ::WideCharToMultiByte(CP_ACP, NULL, strPara.GetBuffer(), wcslen(strPara.GetBuffer()), NULL, 0, NULL, NULL);
char* szAnsi = new char[ansiLen + 1];
::WideCharToMultiByte(CP_ACP, NULL, strPara.GetBuffer(), wcslen(strPara.GetBuffer()), szAnsi, ansiLen, NULL, NULL);
szAnsi[ansiLen] = '\0';
pFile->SendRequest(NULL,0,(LPVOID)szAnsi,ansiLen);
CString strSentence;
DWORD dwStatus;
DWORD dwBuffLen = sizeof(dwStatus);
BOOL bSuccess = pFile->QueryInfo(
HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
&dwStatus, &dwBuffLen);
if( bSuccess && dwStatus>= 200 && dwStatus<300)
{
char buffer[2049];
memset(buffer, 0, 2049);
int nReadCount = 0;
while((nReadCount = pFile->Read(buffer, 2048)) > 0)
{
strReturnValue += buffer;
memset(buffer, 0, 2049);
}
bRet = true;
}
else//错误
bRet = false;
pFile->Close();
sess.Close();
return bRet;
}