用 WinInet 实现POST访问

VS2012测试可用

[cpp]
#include <windows.h>
#pragma comment(lib, "wininet.lib")
#include <wininet.h>
#include <iostream>
#include <string.h>

std::string Post(const char* Url,const char* Path,const char* PostData,const char* Head,bool IsHttps,int Port)
{
HINTERNET hOpen=InternetOpenA("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)",
1,NULL,NULL,NULL);
if(hOpen<=0)return NULL;
HINTERNET hCon=InternetConnectA(hOpen,Url,Port,NULL,NULL,3,NULL,NULL);
if(hCon<=0){
InternetCloseHandle(hOpen);
return NULL;
}
DWORD dwFlags=INTERNET_FLAG_RELOAD|INTERNET_COOKIE_THIRD_PARTY;
std::string Data="";
if(IsHttps==true){
dwFlags=dwFlags|INTERNET_FLAG_SECURE;
}else{
dwFlags=dwFlags|INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS;
}
std::string Headers;
if(Head!=NULL){
Headers=Head;
if(Headers.find("Referer: ")==Headers.npos){
Headers+="Referer: ";
if(IsHttps){
Headers+="https://";
}else{
Headers+="http://";
}
Headers+=Url;Headers+=Path;
}
if(Headers.find("Accept: ")==Headers.npos){
Headers+="\r\nAccept: */*";
}
if(Headers.find("Accept-Language: ")==Headers.npos){
Headers+="\r\nAccept-Language: zh-cn";
}
if(Headers.find("Content-Type: ")==Headers.npos){
Headers+="\r\nContent-Type: application/x-www-form-urlencoded";
}
}

HINTERNET hReq=0;
if(PostData==NULL){
hReq=HttpOpenRequestA(hCon,"GET",Path,"HTTP/1.1" ,NULL,NULL,dwFlags,NULL);
}else{
hReq=HttpOpenRequestA(hCon,"POST",Path,"HTTP/1.1" ,NULL,NULL,dwFlags,NULL);
}
if (hReq<=0){
InternetCloseHandle (hCon);
InternetCloseHandle (hOpen);
return NULL;
}
if(PostData==NULL){
HttpSendRequestA(hReq,Headers.c_str(),Headers.length(),NULL,0);
}else{
char* chTmp=_strdup(PostData);
HttpSendRequestA(hReq,Headers.c_str(),Headers.length(),chTmp,strlen(PostData));
delete chTmp;
}
while (true)
{
char buf[1024]={0};
DWORD Read=0;
InternetReadFile(hReq,buf,1024,&Read);
if(Read<=NULL)break;
Data.append(buf,Read);
}
InternetCloseHandle(hReq);
InternetCloseHandle(hCon);
InternetCloseHandle(hOpen);
return Data;

}
[/cpp]

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据