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方法与服务器通信

posted on 2019-02-20 15:23  布伊什  阅读(1696)  评论(0编辑  收藏  举报