winhttp c++ POST 网页(控制台程序)(整理)

#include <string>
#include <windows.h>
#include <winhttp.h>
#include <vector>
#pragma comment(lib,"winhttp.lib")

using namespace std;


void main()
{


DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPVOID lpOutBuffer = NULL;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;

BOOL bResults = FALSE;

hSession=WinHttpOpen(L"User Agent",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);

if(hSession)
{
hConnect=WinHttpConnect(hSession,L"127.0.0.1",INTERNET_DEFAULT_HTTP_PORT,0);
}

if(hConnect)
{
hRequest=WinHttpOpenRequest(hConnect, L"POST",L"index.php",L"HTTP/1.1", WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
}

LPCWSTR header=L"Content-type: application/x-www-form-urlencoded\r\n";
SIZE_T len = lstrlenW(header);

WinHttpAddRequestHeaders(hRequest, header, DWORD(len), WINHTTP_ADDREQ_FLAG_ADD);

if(hRequest)
{
string data="name=host&sign=xx11sad";
const void *ss = (const char *)data.c_str();

bResults=WinHttpSendRequest(hRequest,0, 0,const_cast<void *>(ss), data.length(), data.length(), 0 );
}

if(bResults)
{
bResults=WinHttpReceiveResponse(hRequest,NULL);
}

if(hRequest){
do{
dwSize = 0;
if(!WinHttpQueryDataAvailable(hRequest, &dwSize)){
printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
}
LPSTR pszOutBuffer;
vector <string> vFileContent;

pszOutBuffer = new char[dwSize + 1];
if(!pszOutBuffer){
printf("Out of memory\n");
dwSize = 0;
}else{
ZeroMemory(pszOutBuffer, dwSize + 1);
if(!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)){
printf("Error %u in WinHttpReadData.\n", GetLastError());
}else{
printf("%s", pszOutBuffer);
vFileContent.push_back(pszOutBuffer);
}
delete[] pszOutBuffer;
}
}while(dwSize > 0);

}

if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);

 

system("pause");


}

posted on 2016-09-30 14:25  混元真人  阅读(469)  评论(0编辑  收藏  举报