C++使用winhttp发起Https Get请求

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
//#include "wininet.h"
#include <winhttp.h>
#include <string.h>
#include <iostream>
#include "cJSON.h"
#include "base64.h"
#pragma comment (lib,"Wininet")
#pragma comment (lib,"Winhttp")
using namespace std;

//每次读取的字节数
#define READ_BUFFER_SIZE        4096

void OutputDebugPrintf(const char * strOutputString, ...)
{
#define PUT_PUT_DEBUG_BUF_LEN 1024
	char strBuffer[PUT_PUT_DEBUG_BUF_LEN] = { 0 };
	va_list vlArgs;
	va_start(vlArgs, strOutputString);
	_vsnprintf (strBuffer, sizeof(strBuffer) - 1, strOutputString, vlArgs); //_vsnprintf_s _vsnprintf
	//vsprintf(strBuffer,strOutputString,vlArgs);
	va_end(vlArgs);
	OutputDebugStringA(strBuffer); //OutputDebugString // OutputDebugStringW
}

BOOL ParseJsonData(const CHAR* szResponseData)
{
	BOOL			bRet = FALSE;
	cJSON			*pJsonData;
	cJSON			*pResult;
	if (NULL == szResponseData)
	{
		goto __CleanUp;
	}
	
	pJsonData= cJSON_Parse(szResponseData);
	if (pJsonData == NULL)
	{
		OutputDebugPrintf("[modiz]cJSON_Parse failed. err = %u",GetLastError());
		goto __CleanUp;
	}
	
	pResult = cJSON_GetObjectItem(pJsonData, "result");
	
	OutputDebugPrintf("[modiz]pResult = %s",pResult->string);

	bRet = TRUE;

__CleanUp:
	return bRet;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	DWORD		dwSize = 0;
	DWORD		dwDownloaded = 0;
	LPSTR		pszOutBuffer;
	BOOL		bResults = FALSE;
	HINTERNET	hSession = NULL;
	HINTERNET	hConnect = NULL;
	HINTERNET	hRequest = NULL;
	LPCWSTR		szHeader = L""; 
	string		strRet = "";
	DWORD		dwPort = 53429;//36020;	//36029

	do 
	{
		++dwPort;
		//1. 初始化一个WinHTTP-session句柄,参数1为此句柄的名称
		hSession = WinHttpOpen(L"WinHTTP",  
			WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
			WINHTTP_NO_PROXY_NAME, 
			WINHTTP_NO_PROXY_BYPASS, 0 );
		if( hSession == NULL)
		{
			OutputDebugPrintf("[modiz]WinHttpOpen Error %u",GetLastError());
			continue;
		}
		
		//2. 通过上述句柄连接到服务器,需要指定服务器IP和端口号。若连接成功,返回的hConnect句柄不为NULL
		hConnect = WinHttpConnect(hSession, L"127.0.0.1",dwPort, 0 );
		if( hConnect == NULL)
		{
			OutputDebugPrintf("[modiz]WinHttpConnect Error %u",GetLastError());
			continue;
		}
		
		//3. 通过hConnect句柄创建一个hRequest句柄,用于发送数据与读取从服务器返回的数据。
		//其中参数2表示请求方式,此处为Get;参数3:给定Get的具体地址,如这里的具体地址为https://127.0.0.1:53530/ECAgent/?op=InitECAgent&arg1=10.70.12.162
		hRequest = WinHttpOpenRequest(hConnect, L"GET", L"ECAgent/?op=InitECAgent&arg1=10.70.12.162",
			NULL, WINHTTP_NO_REFERER, 
			WINHTTP_DEFAULT_ACCEPT_TYPES, 
			WINHTTP_FLAG_SECURE );
		
		if( hRequest == NULL)
		{
			OutputDebugPrintf("[modiz]WinHttpOpenRequest Error %u",GetLastError());
			continue;
		}
		
		
		//4-1. 向服务器发送数据
		//(1) 发送请求
		bResults = WinHttpSendRequest( hRequest,
			szHeader, wcslen(szHeader),
			WINHTTP_NO_REQUEST_DATA, 0, 
			0, 0 );
		
		if( bResults == NULL)
		{
			OutputDebugPrintf( "[modiz]WinHttpSendRequest Error %u",GetLastError());
			continue;
		}
		
		//(3)发送请求成功则准备接受服务器的response。
		//注意:在使用 WinHttpQueryDataAvailable和WinHttpReadData前必须使用WinHttpReceiveResponse才能access服务器返回的数据
		bResults = WinHttpReceiveResponse(hRequest, NULL );
		
		// Keep checking for data until there is nothing left.
		if( bResults )
		{
			do 
			{
				//(1) 获取返回数据的大小(以字节为单位)
				dwSize = 0;
				if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
				{
					OutputDebugPrintf( "Error %u in WinHttpQueryDataAvailable.\n",GetLastError( ) );
					break;
				}

				//(2) 根据返回数据的长度为buffer申请内存空间
				pszOutBuffer = new(std::nothrow) char[dwSize+1];
				if( !pszOutBuffer )
				{
					OutputDebugPrintf( "Out of memory\n" );
					dwSize=0;
					break;
				}
				else
				{
					ZeroMemory( pszOutBuffer, dwSize+1 );
					
					//(3) 通过WinHttpReadData读取服务器的返回数据
					if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded ) )
					{
						OutputDebugPrintf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
					}
					else
					{
						strRet.append(pszOutBuffer);
						OutputDebugPrintf( "%s", pszOutBuffer );
					}
					
					// 释放分配内存
					delete [] pszOutBuffer;
				}
			} while( dwSize > 0 );
		}
	} while (FALSE);
	
	// Report any errors.
	if( !bResults )
	{
		OutputDebugPrintf("WinHttpReceiveResponse Error %d has occurred.\n", GetLastError( ) );
	}
	OutputDebugPrintf( "[modiz]strRet: %s", strRet.c_str() );

	ParseJsonData(strRet.c_str());

	// Close any open handles.
	if( hRequest ) WinHttpCloseHandle( hRequest );
	if( hConnect ) WinHttpCloseHandle( hConnect );
	if( hSession ) WinHttpCloseHandle( hSession );

	return 0;
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
c# winhttp发送get请求可以使用HttpClient或者HttpWebRequest类来实现。下面是使用HttpClient类的示例代码: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main() { using var client = new HttpClient(); var response = await client.GetAsync("http://example.com"); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } } ``` 上面的代码首先创建一个HttpClient对象,然后调用GetAsync方法发送GET请求,参数是URL地址。接着使用EnsureSuccessStatusCode方法确保请求成功。最后使用ReadAsStringAsync方法读取响应内容并输出到控制台。 对于更底层的网络请求,可以使用HttpWebRequest类来实现。以下是使用HttpWebRequest类的示例代码: ```csharp using System; using System.IO; using System.Net; class Program { static void Main() { var request = WebRequest.Create("http://example.com") as HttpWebRequest; request.Method = "GET"; var response = request.GetResponse() as HttpWebResponse; using var streamReader = new StreamReader(response.GetResponseStream()); var content = streamReader.ReadToEnd(); Console.WriteLine(content); } } ``` 上面的代码首先创建一个HttpWebRequest对象,然后设置Method属性为"GET",即发送GET请求。接着使用GetResponse方法发送请求并获取响应。最后使用StreamReader类读取响应流并输出到控制台。 总结一下,以上两种方式都可以用来发送GET请求,并获取响应内容。根据个人使用习惯和需要选择适合的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值