使用 SendRequestEx() 上报数据

来源:互联网 发布:程序员博客系统 编辑:程序博客网 时间:2024/04/28 05:16
//上报数据
//http://bbs.csdn.net/topics/320259464
//http://bbs.csdn.net/topics/100121753
BOOL ReportData_V1(CString sHost, CString sData, CString &sError)
{
try
{
//解析URL(可省)
CString sServer = "";
CString sObject = "";
INTERNET_PORT nPort = 0;
DWORD dwServiceType = 0;
if (!AfxParseURL(sHost, dwServiceType, sServer, sObject, nPort))
{
//Url不是有效有网络地址
return FALSE;
}


//===Only for test===
//sHost = "http://updata.nmenu.net/";
//sData = "userid=123&usermac=74-D4-35-8A-D0-7E&gameid=1&gamename=cps";




//连接服务器
//CInternetSession * session = new CInternetSession();
//CInternetSession session(_T("session"), 0, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_FLAG_DONT_CACHE);
CInternetSession session;
session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 3000);
session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);
session.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 3000);
session.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 3000);


CHttpConnection* pServer = session.GetHttpConnection(sServer, nPort, NULL, NULL);
if (NULL == pServer)
{
//服务器连接失败
sError.Format("Failed to connect server: %s.\r\n", sServer);
session.Close();
return FALSE;
}


//登陆页面
CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, sObject);
if (NULL == pFile)
{
//找不到网络地址
sError.Format("Failed to open post request.\r\n");
pServer->Close();
session.Close();
return FALSE;
}


//发送数据
#if 1   //方法I:
if (!pFile->SendRequestEx((DWORD)sData.GetLength()))
{
sError.Format("Failed to send request.\r\n");
pServer->Close();
session.Close();
pFile->Close();
return FALSE;
}
pFile->WriteString((LPCTSTR)(LPCSTR)sData);
pFile->EndRequest(); //这一步总是抛出异常
#else
//方法II:
BOOL bSucc = pFile->SendRequest(NULL, 0, (LPTSTR)(LPCTSTR)sData, sData.GetLength());
#endif


//查询状态及返回数据
DWORD dwRet = 0;
pFile->QueryInfoStatusCode(dwRet);
if (dwRet == HTTP_STATUS_OK)
{
int nReadCount = 0;
CString strLine = "";
CString strHtml = "";
while ((nReadCount = pFile->ReadString(strLine)) > 0)
{
strHtml += strLine;
}
}


//释放
pFile->Close();
pServer->Close();
session.Close();
}
catch (CInternetException* e)
{
e->m_dwContext;
e->ReportError();


char err[500] = {0};
e->GetErrorMessage(err, 500);
CString str;
str.Format("InternetException occur!\r\n%s error code=%d", err, GetLastError());
AfxMessageBox(str);
}
catch (CFileException& fe)
{
fe.ReportError();
CString str;
str.Format("FileException occur!\r\n%d", fe.m_lOsError);
//AfxMessageBox(str);
}
catch (...)
{
CString str;
str.Format("Unknow Exception occur!\r\n%d", GetLastError());
//AfxMessageBox(str);
}


return TRUE;
}
0 0
原创粉丝点击