1. 程式人生 > >HTTP GET請求

HTTP GET請求

form unsigned file bool port con ica server nec

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.返回結果

技術分享圖片

HTTP GET請求