用VC或者socket实现GET网页数据的方法用得多了,近日看了一下用VC实现POST网页的方法,总结了以下的一个函数:
#include "afxinet.h" bool PostData(LPCTSTR host, LPCTSTR object, LPCTSTR postdata, LPCTSTR refererlink, int port) { CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded"); strHeaders += "rnAccept-Language:zh-cn"; if(refererlink) { strHeaders += "rnReferer:"; strHeaders += refererlink; } CString strFormData = _T(postdata); CInternetSession session; CHttpConnection* pConnection = session.GetHttpConnection(_T(host)); if(pConnection == NULL) return false; CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T(object)); if(pFile == NULL) return false; BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)strFormData, strFormData.GetLength()); if(result == FALSE) return false; DWORD dwRet; pFile->QueryInfoStatusCode(dwRet); CString m_strHtml=""; char szBuff[1024]; UINT nRead; while ((nRead = pFile->Read(szBuff,1023))>0) { m_strHtml+=CString(szBuff,nRead); } FILE *fp = fopen("C:\11.html", "w"); fwrite(m_strHtml, 1, m_strHtml.GetLength(), fp); fclose(fp); if (dwRet == HTTP_STATUS_OK) { return true; } return false; }
转载请注明:爱开源 » 用VC实现POST数据的方法