欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++发送http请求winnet的代码实例

程序员文章站 2024-01-29 23:15:28
写之前网上也有找 不过可以发送http请求 但是不能发送数据与是做了改进 //模拟浏览器发送HTTP请求函数 //地址,端口,跳转路径,方法,数据,数据长度 std::s...

写之前网上也有找 不过可以发送http请求 但是不能发送数据与是做了改进

//模拟浏览器发送HTTP请求函数
//地址,端口,跳转路径,方法,数据,数据长度
std::string HttpRequest(char * lpHostName,short sPort,char * lpUrl,char * lpMethod,char * lpPostData,int nPostDataLen)  
{  
    HINTERNET hInternet,hConnect,hRequest;  
  
    BOOL bRet;  
  
    std::string strResponse;  
	// 建立会话
    hInternet = (HINSTANCE)InternetOpen("User-Agent",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);  
    if(!hInternet)  
        goto Ret0;  
	// 建立连接
    //hConnect = (HINSTANCE)InternetConnect(hInternet,lpHostName,sPort,NULL,"HTTP/1.1",INTERNET_SERVICE_HTTP,0,0);
	hConnect = (HINSTANCE)InternetConnect(hInternet,lpHostName,sPort,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
    if(!hConnect)  
        goto Ret0;  
  //建立一个 HTTP 请求
	hRequest = (HINSTANCE)HttpOpenRequest(hConnect,_T(lpMethod),lpUrl,_T("HTTP/1.1"),lpUrl,NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
    //hRequest = (HINSTANCE)HttpOpenRequestW(hConnect,new WCHAR[CString(lpMethod).GetLength()+1],new WCHAR[CString(lpUrl).GetLength()+1],_T("HTTP/1.1"),lpUrl,NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
	if(!hRequest)  
        goto Ret0;  
    //bRet = HttpAddRequestHeaders(hRequest,"Content-Type: application/x-www-form-urlencoded",Len(FORMHEADERS),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);  
    //if(!bRet)  
        //goto Ret0;  
	//发送请求
	TCHAR* postheader = _T("Content-Type: application/x-www-form-urlencoded");
    bRet = HttpSendRequest(hRequest,postheader,-1,lpPostData,strlen(lpPostData));  
    while(TRUE)  
    {  
        char cReadBuffer[4096];  
        unsigned long lNumberOfBytesRead;  
		//下载HTTP服务器上的资源了。
        bRet = InternetReadFile(hRequest,cReadBuffer,sizeof(cReadBuffer) - 1,&lNumberOfBytesRead);  
        if(!bRet || !lNumberOfBytesRead)  
            break;  
        cReadBuffer[lNumberOfBytesRead] = 0;  
        strResponse = strResponse + cReadBuffer;  
    }  
  
 Ret0:  
    if(hRequest)  
        InternetCloseHandle(hRequest);  
    if(hConnect)  
        InternetCloseHandle(hConnect);  
    if(hInternet)  
        InternetCloseHandle(hInternet);  
  
    return strResponse;  
} ; 
  

可以直接用头部加上

#include "Wininet.h"

#pragma comment(lib,"Wininet.lib")