//给指定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会等待几十秒, 感觉像卡死了似的.