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方法与服务器通信
原文:https://www.cnblogs.com/buyishi/p/10406877.html