CInternetSession CHttpFile Post提交數據


//給指定url發請求, 返回請求后的結果
string CAutoPatchDlg::SendURLPost(string strServerName, string strFormActionUrl, string strPostStr)
{
	CString strFormData(strPostStr.c_str());    // 需要提交的數據
CInternetsess sess("HttpClient");

//連結超時沒效果的, 發送超時與接收超時有用, 連結超時可以用多線程WaitForSingleObject來實現
sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5000); // 5000毫秒的連接超時
sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 5000); // 5000毫秒的發送超時
sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 5000); // 5000毫秒的接收超時
sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 5000); // 5000毫秒的發送超時
sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 5000); // 5000毫秒的接收超時
sess.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); // 1次重試

	CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded"); // 請求頭
	CHttpConnection *pConnection = sess.GetHttpConnection(strServerName.c_str());
	CHttpFile *pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, strFormActionUrl.c_str());
	
	CString strSentence, strGetSentence = "";
	if(pFile)
	{
		BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strFormData, strFormData.GetLength());
		while(pFile->ReadString(strSentence))  // 讀取提交數據后的返回結果
			strGetSentence = strGetSentence + strSentence + char(13) + char(10);
		pFile->Close();
		delete pFile;
		sess.Close();
		return string(strGetSentence.GetBuffer());
	}
	return "";
}

  

string strResult = "";
	string strServerName = "www.test.com";
	string strFormActionUrl = "/index.php";
	string strPostData = "username=" + strUserName + "&password=" + strPassword;
strResult = SendURLPost(strServerName, strFormActionUrl, strPostData);

  

這個方法有個缺陷, 網絡不通SendRequest會等待幾十秒, 感覺像卡死了似的.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM