设为首页 加入收藏

TOP

c++发送http请求winnet的代码实例
2018-03-13 09:06:32 】 浏览:281
Tags:发送 http 请求 winnet 代码 实例

写之前网上也有找 不过可以发送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")

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇c++发送http请求chttpcile代码实例 下一篇c++函数包装器实现教程

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目