您的位置:首页 > 理论基础 > 计算机网络

C++ http请求

2016-01-03 00:55 555 查看
实例 代码

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <wininet.h>
#include <iostream>
#include <string>
using namespace std;

#define MAXSIZE 1024
#pragma comment(lib, "Wininet.lib")

bool  Urlopen(const _TCHAR* url, BYTE *&urlContent)
{
HINTERNET hSession = InternetOpen(_T("UrlTest"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hSession != NULL)
{
HINTERNET hHttp = InternetOpenUrl(hSession, url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
if (hHttp != NULL)
{
urlContent = new (std::nothrow) BYTE[MAXSIZE];
if(NULL == urlContent)
{
return false;
}
memset(urlContent, 0, MAXSIZE);
ULONG Number = 1;

bool bInternetReadFile = false;

bInternetReadFile = InternetReadFile(hHttp, urlContent, MAXSIZE - 1, &Number);
if(!bInternetReadFile)
{
return false;
}

if(Number <= 0 || Number >= <span style="font-family: Arial, Helvetica, sans-serif;">MAXSIZE</span>)
{
return false;
}

urlContent[Number] = '\0';

InternetCloseHandle(hHttp);
hHttp = NULL;

return true;
}
InternetCloseHandle(hSession);
hSession = NULL;
}

return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
wstring wstr = _T("http://120.25.242.254/WxService/test?UserId=niebingyu&OrgCode=YUTONGXUN5.0");

BYTE* byte = NULL;

bool bUrlopen = false;
bUrlopen = Urlopen(wstr.c_str(), byte);
if(NULL == byte)
{
cout<<"byte is NULL"<<endl;
return 0;
}

if(!bUrlopen)
{
cout<<"Urlopen return false"<<endl;
return 0;
}

cout<<byte<<endl;

if(NULL != byte)
{
delete byte;
byte = NULL;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: