MFC HTTP(S)請求筆記


GET示例

#include <afxinet.h>
#include <iostream>
#include <vector>
#ifdef _UNICODE
#define COUT wcout
#else
#define COUT cout
#endif
using namespace std;
int main()
{
    CInternetSession session(TEXT("MfcHttp"));
    CHttpConnection *connection = session.GetHttpConnection(TEXT("example.com"), (INTERNET_PORT)80);
    CHttpFile *file = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET, TEXT(""));
    try
    {
        file->SendRequest();
        DWORD statusCode;
        file->QueryInfoStatusCode(statusCode);
        if (HTTP_STATUS_OK == statusCode)
        {
            CString contentLength;
            file->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, contentLength);
            int fileSize = _ttoi(contentLength);
            vector<char> buffer(fileSize + 1);
            UINT numberOfBytesRead = file->Read(&buffer[0], fileSize);
            buffer[fileSize] = '\0';
            COUT << &buffer[0] << endl;
        }
        else
        {
            COUT << "statusCode" << statusCode << endl;
        }
    }
    catch (CInternetException *ex)
    {
        TCHAR error[1024];
        ex->GetErrorMessage(error, 1024);
        COUT << error << endl;
        ex->Delete();
    }
    delete file;
    delete connection;
    system("pause");
    return 0;
}

若要訪問HTTPS鏈接,應將上述代碼中的

CHttpConnection *connection = session.GetHttpConnection(TEXT("example.com"), (INTERNET_PORT)80);
CHttpFile *file = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET, TEXT(""));

更改為

CHttpConnection *connection = session.GetHttpConnection(TEXT("www.example.com"), INTERNET_FLAG_SECURE, (INTERNET_PORT)443);
CHttpFile *file = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET, TEXT(""), nullptr, 1, nullptr, nullptr, INTERNET_FLAG_SECURE);

參考博文:MFC使用HttpGet和HttpPost方法與服務器通信


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM