C++ http請求
阿新 • • 發佈:2019-01-23
例項 程式碼
#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; }