头文件:
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <windows.h>
#include <string>
#include <cstring>
#include <string.h>
#include <stdlib.h>
#include <cstringt.h>
#include <atlstr.h>
#include <objbase.h>
#include <atlconv.h>
using namespace std;
// TODO: 在此处引用程序需要的其他头文件
.cpp:
// HttpRequest_Demo1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#import "C:\\Windows\\System32\\winhttp.dll" no_namespace
//ANSI转UTF8
void ConvertANSIToUTF8(string& nDst, const char* strANSI)
{
//将ANSI字符串转Unicode格式
int nLen = ::MultiByteToWideChar(CP_ACP, 0, strANSI, -1, NULL, 0);
WCHAR* wStr = new WCHAR[nLen + 1];
memset(wStr, 0, sizeof(wStr));
//使用缓冲区接收
nLen = MultiByteToWideChar(CP_ACP, 0, strANSI, -1, wStr, nLen);
//将Unicode格式转UTF8格式
int uLen = WideCharToMultiByte(CP_UTF8, 0, wStr, -1, NULL, 0, NULL, NULL);
char *szUTF8 = new char[uLen + 1];
memset(szUTF8, 0, sizeof(szUTF8));
//使用缓冲区接收
WideCharToMultiByte(CP_UTF8, 0, wStr, -1, szUTF8, uLen, NULL, NULL);
nDst = szUTF8;
delete[]wStr;
wStr = NULL;
delete[] szUTF8;
szUTF8 = NULL;
}
//UTF8转ANSI
void ConvertUTF8ToANSI(string& nDst, const char* strUTF8)
{
//将UTF8字符串转Unicode格式
int nLen = ::MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, NULL, 0);
WCHAR* wStr = new WCHAR[nLen + 1];
memset(wStr, 0, sizeof(wStr));
//使用缓冲区接收
nLen = MultiByteToWideChar(CP_UTF8, 0, strUTF8, -1, wStr, nLen);
//将Unicode格式转ANSI格式
int uLen = WideCharToMultiByte(CP_ACP, 0, wStr, -1, NULL, 0, NULL, NULL);
char *szANSI = new char[uLen + 1];
memset(szANSI, 0, sizeof(szANSI));
//使用缓冲区接收
WideCharToMultiByte(CP_ACP, 0, wStr, -1, szANSI, uLen, NULL, NULL);
nDst = szANSI;
delete[]wStr;
wStr = NULL;
delete[] szANSI;
szANSI = NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
//以单线程创建初始化com对象
CoInitialize(NULL);
IWinHttpRequest *win = NULL;
//根据给定的程序标识符从注册表找出对应的类标识符
CLSID clsid = { 0 };
HRESULT hr = CLSIDFromProgID(_T("WinHttp.WinHttpRequest.5.1"), &clsid);
if (FAILED(hr))
return -1;
//用指定的类标识符创建一个com对象
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, __uuidof(IWinHttpRequest), (LPVOID*)&win);
if (FAILED(hr))
return -1;
//打开http连接
hr = win->Open(_T("GET"), _T("http://www.baidu.com"));
if (FAILED(hr))
return -1;
//发送请求
hr = win->Send();
if (FAILED(hr))
return -1;
//接收返回数据并进行相应转码
_bstr_t Rtn = win->ResponseText;
const char *buf = Rtn;
string strRtn = buf;
ConvertANSIToUTF8(strRtn, buf);
//写入
DWORD dwWrite;
HANDLE hFile = CreateFile(_T("F:\\Zyh\\vc++demo\\HttpRequest_Demo1\\1.html"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
WriteFile(hFile, strRtn.c_str(), strlen(strRtn.c_str())+1, &dwWrite, NULL);
win->Release();
//关闭当前线程的com
CoUninitialize();
return 0;
}