首页 > 编程语言 > 详细

MFC HTTP(S)请求笔记

时间:2019-02-20 15:33:49      阅读:214      评论:0      收藏:0      [点我收藏+]

GET示例

#include <afxinet.h>
#include <iostream>
#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);
            char *buffer = new char[fileSize + 1];
            UINT numberOfBytesRead = file->Read(buffer, fileSize);
            buffer[fileSize] = \0;
            COUT << buffer << endl;
            delete buffer;
        }
        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方法与服务器通信

MFC HTTP(S)请求笔记

原文:https://www.cnblogs.com/buyishi/p/10406877.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!