HTTP GET请求
1.接口实现
CString HttpGetRequest(CString strServerName, int nPort, CString strUrl, CString sParam) { if (strServerName.IsEmpty()) { return ""; } if (strServerName.Mid(strServerName.GetLength() - 1, 1) == "/") { strServerName = strServerName.Mid(0, strServerName.GetLength() - 1); } if (strServerName.Find(L"http://") == 0) { int nLength = strlen("http://"); strServerName = strServerName.Mid(nLength, strServerName.GetLength() - nLength); } if (strServerName.Find(L"https://") == 0) { int nLength = strlen("https://"); strServerName = strServerName.Mid(nLength, strServerName.GetLength() - nLength); } HINTERNET hInternet = (HINSTANCE)InternetOpen(L"User-Agent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (!hInternet) { return ""; } HINTERNET hConnect = (HINSTANCE)InternetConnect(hInternet, strServerName, nPort, NULL, L"HTTP/1.1", INTERNET_SERVICE_HTTP, 0, 0); if (!hConnect) { if (hInternet) InternetCloseHandle(hInternet); return ""; } CString strRequestParam = strUrl; if (!sParam.IsEmpty()) { strRequestParam = strUrl + L"?" + sParam; } HINTERNET hRequest = (HINSTANCE)HttpOpenRequest(hConnect, L"GET", strRequestParam, L"HTTP/1.1", NULL, NULL, INTERNET_FLAG_RELOAD, 0); if (!hRequest) { if (hConnect) InternetCloseHandle(hConnect); if (hInternet) InternetCloseHandle(hInternet); return ""; } bool bRet; //bRet = HttpAddRequestHeaders(hRequest,"Content-Type: application/x-www-form-urlencoded",Len(FORMHEADERS),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD); bRet = HttpSendRequest(hRequest, NULL, 0, NULL, 0); std::string strResponse; while (TRUE) { char cReadBuffer[4096]; unsigned long ulReadByteSize; bRet = InternetReadFile(hRequest, cReadBuffer, sizeof(cReadBuffer)-1, &ulReadByteSize); if (!bRet || !ulReadByteSize)break; cReadBuffer[ulReadByteSize] = 0; strResponse = strResponse + cReadBuffer; } if (hRequest) InternetCloseHandle(hRequest); if (hConnect) InternetCloseHandle(hConnect); if (hInternet) InternetCloseHandle(hInternet); CString csResponse = UTOCS(strResponse); return csResponse; }
2.调用测试
CString sRet = TaskMgr::GetInstance()->HttpGetRequest("https://passport.cnblogs.com", 80, "agreement.html", "");
3.返回结果
ps:本博文只用于日常备注及学习交流,请勿用于任何商业用途,涉及网摘等资料如有侵犯原作者权利,请联系确保及时更正!