方法1:
#include <afxwin.h>
#include <stdio.h>
#include <windows.h>
#include "Wininet.h"
#include <WinSock2.h>
#pragma comment(lib,"Wininet.lib")
#pragma comment(lib,"nafxcwd.lib")
#pragma comment(lib, "ws2_32.lib")
//模拟浏览器发送HTTP请求函数
CString HttpRequest(TCHAR * lpHostName,short sPort,TCHAR * lpUrl,TCHAR * lpMethod,TCHAR * lpPostData,int nPostDataLen)
{
HINTERNET hInternet,hConnect,hRequest;
BOOL bRet;
CString strResponse;
FILE * fp ;
static TCHAR *accept = _T("Accept: */*");
TCHAR hdrs[] = L"Content-Type: application/x-www-form-urlencoded"
L"Accept-Language: zh-cn"
L"Accept-Encoding: gzip, deflate"
L"Pragma: no-cache";
hInternet = InternetOpen(L"User-Agent",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if(!hInternet)
goto Ret0;
hConnect = InternetConnect(hInternet,lpHostName, INTERNET_DEFAULT_HTTP_PORT,NULL, NULL, INTERNET_SERVICE_HTTP,0,1);
if(!hConnect)
goto Ret0;
hRequest = HttpOpenRequest(hConnect, lpMethod, lpUrl, L"HTTP/1.1", NULL, NULL, INTERNET_FLAG_RELOAD, 1);
DWORD erro = GetLastError();
if(!hRequest)
goto Ret0;
bRet = HttpSendRequest(hRequest,hdrs, wcslen(hdrs), "key=love&go=go&y=1",strlen("key=love&go=go&y=1"));
fp = fopen("C://a.html","w");
while(TRUE)
{
char cReadBuffer[4096];
unsigned long lNumberOfBytesRead;
bRet = InternetReadFile(hRequest,cReadBuffer,sizeof(cReadBuffer) - 1,&lNumberOfBytesRead);
if(!bRet || !lNumberOfBytesRead)
break;
cReadBuffer[lNumberOfBytesRead] = 0;
strResponse = strResponse + cReadBuffer;
fwrite(cReadBuffer,lNumberOfBytesRead,1,fp);
}
fclose(fp);
Ret0:
if(hRequest)
InternetCloseHandle(hRequest);
if(hConnect)
InternetCloseHandle(hConnect);
if(hInternet)
InternetCloseHandle(hInternet);
return strResponse;
}
void main(int argc, char *argv[])
{
CString strResponse = HttpRequest(L"lrc.bzmtv.com",80,L"/So.asp", L"POST", L"key=love&go=go&y=1",wcslen(L"key=love&go=go&y=1"));
}
方法2
在vc中如何用post方法提交表单
func(){
CInternetSession m_InetSession("session");
CHttpConnection* pServer = NULL;
CHttpFile* pFile = NULL;
try{
INTERNET_PORT nPort;
nPort=80;
pServer = m_InetSession.GetHttpConnection(m_strServerName, nPort);
pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,
m_strObjectName);
char szHeaders[100];
strcpy(szHeaders,"Accept: text*/*/r/nContent-Type: application/x-www-form-urlencoded");
pFile->AddRequestHeaders(szHeaders);
pFile->SendRequestEx(m_strRequest.GetLength());
pFile->WriteString(m_strRequest); //重要-->m_Request 中有"name=aaa&name2=BBB&..."
pFile->EndRequest();
DWORD dwRet;
pFile->QueryInfoStatusCode(dwRet);
CString str;
m_Mutex.Lock();
m_strHtml="";
char szBuff[1024];
if (dwRet == HTTP_STATUS_OK){
UINT nRead;
while ((nRead = pFile->Read(szBuff,1023))>0)
{
m_strHtml+=CString(szBuff,nRead);
}
}
m_Mutex.Unlock();
delete pFile;
delete pServer;
}
catch (CInternetException* e){
CString s;
s.Format("Internet Exception/r/nm_dwError%u,m_dwContextError%u",e->m_dwError,e->m_dwContext);
AfxMessageBox(s);
//catch errors from WinInet
}