构建CHttpSession 类来实现网页数据的请求
最近实现了一个简单的CHttpSession类,用来请求制定URL的网页,支持POST传送方式和cookie机制。当然使用了CInternetSession,CHttpConnection和CHttpFile类,但我没有继承CInternetSession类。 POST支持的函数如下: BOOL CHttpSession::SendData(CHttpFile * pFile,LPCSTR pszPostForm /**/ /*=NULL*/ ) ... { ASSERT(pFile!=NULL); BOOL bResult=TRUE; if(pszPostForm!=NULL) ...{ CString strFormData(pszPostForm); //post data CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded"); // URL-encoded form variables - bResult=pFile->SendRequest(strHeaders,(LPVOID)(LPCTSTR)strFormData,strFormData.GetLength()); TRACE("post data:%s/n",pszPostForm); } else ...{ bResult=pFile->SendRequest(); } CString strReqHead,strRepHead; if(bResult) ...{ //#ifdef _DEBUG DWORD dw=1; pFile->QueryInfo(HTTP_QUERY_RAW_HEADERS_CRLF,strRepHead); pFile->QueryInfoStatusCode(_nStatus); BOOL bResult=TRUE; bResult=pFile->QueryInfo(HTTP_QUERY_FLAG_REQUEST_HEADERS|HTTP_QUERY_RAW_HEADERS_CRLF,strReqHead.GetBufferSetLength(dw),&dw,0); if(!bResult && GetLastError()==ERROR_INSUFFICIENT_BUFFER) ...{ bResult=pFile->QueryInfo(HTTP_QUERY_FLAG_REQUEST_HEADERS|HTTP_QUERY_RAW_HEADERS_CRLF,0); } //szBuffer[dw]='/0'; //strReqHead=CString(szBuffer); //int nLen=strReqHead.ReverseFind('/n')+1; strReqHead.ReleaseBuffer(dw); //CString strTmp; //strTmp.Format("http req head:/n%s/n/n http rep head:/n%s",strReqHead,strRepHead); //TRACE(strTmp); //#endif TRACE("http req head:/n%s/n",strReqHead); TRACE("http rep head:/n%s/n",strRepHead); _strRepHead=strRepHead; _strReqHead=strReqHead; } else ...{ TRACE("send req error!/n"); } return bResult; } 设置COOKIE相对简单些,直接调用CInternetSession类中的函数实现: void CHttpSession::GetCookie(CString & strCookie,LPCTSTR pszUrl) ... @H_502_317@{ ASSERT(AfxIsValidString(pszUrl)); //cookie叠加 if(IsSameSite(_strUrl,pszUrl)) ...{ TRACE("same site for cookie!/n"); } //得到存储的cookie strCookie=_T(""); DWORD dwCookieLen=CInternetSession::GetCookieLength(pszUrl,""); if(dwCookieLen>0) ...{ BOOL bRet=CInternetSession::GetCookie(pszUrl,"",strCookie); //strCookie.ReleaseBuffer(2*dwCookieLen/sizeof(TCHAR)); TRACE("cookie=%s/n",strCookie); if(!bRet) ...{ strCookie=_T(""); TRACE("得到cookie失败!/n"); } } _strUrl=CString(pszUrl); } @H_437_301@ 类的引用格式如下: ??httpSession.SetPost(_T("UserID"),_T("luo31")); ??//go session ??httpSession.StartGetReq("http://www.sohu.com/login.html/mail.asp");? ? ?(编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |