mfc: http请求get/post

本文介绍如何在MFC应用中执行HTTP GET和POST请求,用户可在输入框输入HTTP请求,程序将返回JSON格式的响应数据。
摘要由CSDN通过智能技术生成

效果:
在IDC_EDIT_HTTP_INPUT 输入http请求
在IDC_EDIT_HTTP_OUTPUT 反馈返回数据json格式的
在这里插入图片描述


void CTG_HelperDlg::OnBnClickedButtonSubmit()
{
   
	CString str;
GetDlgItem(IDC_EDIT_HTTP_INPUT)->GetWindowText(str);
AppendToOutput(str);
 
CString rsp = L"";
CString post_data = L"";
ExecuteRequest(
			  L"GET",
			  str,
			  post_data,
			  rsp
			  );
TRACE("rsp:%s",rsp);
}

void CTG_HelperDlg::AppendToOutput(CString str)
{
   
	  
str =  _T("\r\n") + str;
CEdit* http_output_editbox = (CEdit*)GetDlgItem(IDC_EDIT_HTTP_OUTPUT);

//在末尾添加内容
int nCount    = 0;
int nLastLineStart = 0;
int nLastLineEnd = 0;
nCount         =  http_output_editbox->GetLineCount();              //获取行数,包括回车行
//MessageBox(nCount);
nLastLineStart    =  http_output_editbox->LineIndex( nCount - 1 );   //获取字符数,许可多行
nLastLineEnd    
您可以按照以下步骤实现: 1. 打开文件对话框,让用户选择需要上传的图片文件,可以使用 CFileDialog 类实现。 2. 将选择的文件路径保存到一个字符串数组。 3. 使用 WinHTTP API 发送 HTTP POST 请求,并将文件作为二进制数据附加到请求。可以使用 CHttpFile 类实现。 4. 在请求头添加必要的信息,例如 Content-Type、Content-Length 等。 5. 在请求体添加每个文件的二进制数据,并在每个文件数据前添加一个分隔符。 6. 发送请求并等待响应,处理响应结果。 下面是一个简单的示例代码,仅供参考: ```cpp void CMyDlg::OnUploadBtnClicked() { // 打开文件对话框,选择需要上传的图片文件 CStringArray arrFileNames; CFileDialog dlg(TRUE, NULL, NULL, OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST, _T("图片文件 (*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png||"), this); dlg.m_ofn.lpstrFile = new TCHAR[MAX_PATH * 100]; dlg.m_ofn.nMaxFile = MAX_PATH * 100; if (dlg.DoModal() == IDOK) { POSITION pos = dlg.GetStartPosition(); while (pos != NULL) { CString strFileName = dlg.GetNextPathName(pos); arrFileNames.Add(strFileName); } } delete[] dlg.m_ofn.lpstrFile; // 发送 HTTP POST 请求,上传图片文件 CString strBoundary = _T("----MyBoundary1234567890"); CString strContentType = _T("multipart/form-data; boundary=") + strBoundary; CString strHost = _T("169.254.1.10"); CString strUrl = _T("/api/v1/~bali/ABC0123456789"); CInternetSession session; CHttpConnection* pConnection = session.GetHttpConnection(strHost); if (pConnection != NULL) { CString strHeaders = _T("Content-Type: ") + strContentType + _T("\r\n"); CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, strUrl, NULL, 1, NULL, NULL, INTERNET_FLAG_DONT_CACHE); if (pFile != NULL) { // 添加请求头 pFile->AddRequestHeaders(strHeaders, HTTP_ADDREQ_FLAG_REPLACE); // 计算请求体长度 ULONGLONG nContentLength = CalcRequestContentLength(arrFileNames, strBoundary); // 添加请求体 if (pFile->SendRequestEx(nContentLength, HSR_SYNC | HSR_INITIATE)) { AddRequestContent(arrFileNames, strBoundary, pFile); pFile->EndRequest(HSR_SYNC | HSR_TERMINATE); // 处理响应结果 DWORD dwStatusCode; pFile->QueryInfoStatusCode(dwStatusCode); if (dwStatusCode == HTTP_STATUS_OK) { // 上传成功 AfxMessageBox(_T("上传成功!")); } else { // 上传失败 AfxMessageBox(_T("上传失败!")); } } else { // 发送请求失败 AfxMessageBox(_T("发送请求失败!")); } pFile->Close(); delete pFile; } else { // 打开请求失败 AfxMessageBox(_T("打开请求失败!")); } pConnection->Close(); delete pConnection; } else { // 建立连接失败 AfxMessageBox(_T("建立连接失败!")); } } ULONGLONG CMyDlg::CalcRequestContentLength(const CStringArray& arrFileNames, const CString& strBoundary) { ULONGLONG nLength = 0; // 计算每个文件的长度 for (int i = 0; i < arrFileNames.GetSize(); i++) { CString strFileName = arrFileNames[i]; CFile file; if (file.Open(strFileName, CFile::modeRead | CFile::shareDenyWrite)) { nLength += strBoundary.GetLength() + 2; // 添加分隔符和换行符 nLength += GetFileContentLength(&file); // 添加文件内容长度 nLength += 2; // 添加换行符 file.Close(); } } // 添加结束分隔符和换行符 nLength += strBoundary.GetLength() + 2 + 2; return nLength; } ULONGLONG CMyDlg::GetFileContentLength(CFile* pFile) { ULONGLONG nLength = 0; if (pFile != NULL) { nLength = pFile->GetLength(); } return nLength; } void CMyDlg::AddRequestContent(const CStringArray& arrFileNames, const CString& strBoundary, CHttpFile* pFile) { // 添加每个文件的内容 for (int i = 0; i < arrFileNames.GetSize(); i++) { CString strFileName = arrFileNames[i]; CFile file; if (file.Open(strFileName, CFile::modeRead | CFile::shareDenyWrite)) { CString strContentDisposition = _T("Content-Disposition: form-data; name=\"file\"; filename=\"") + GetFileName(strFileName) + _T("\"\r\n"); CString strContentType = _T("Content-Type: application/octet-stream\r\n"); CString strContentLengthHeader = _T("Content-Length: ") + FormatFileSize(GetFileContentLength(&file)) + _T("\r\n"); CString strCRLF = _T("\r\n"); // 添加分隔符和请求头 pFile->Write((LPCTSTR)strBoundary, strBoundary.GetLength()); pFile->Write(_T("\r\n"), 2); pFile->Write((LPCTSTR)strContentDisposition, strContentDisposition.GetLength()); pFile->Write((LPCTSTR)strContentType, strContentType.GetLength()); pFile->Write((LPCTSTR)strContentLengthHeader, strContentLengthHeader.GetLength()); pFile->Write((LPCTSTR)strCRLF, strCRLF.GetLength()); // 添加文件内容 BYTE buffer[4096]; UINT nBytesRead; while ((nBytesRead = file.Read(buffer, 4096)) > 0) { pFile->Write(buffer, nBytesRead); } // 添加换行符 pFile->Write((LPCTSTR)strCRLF, strCRLF.GetLength()); file.Close(); } } // 添加结束分隔符和换行符 CString strEndBoundary = strBoundary + _T("--"); pFile->Write((LPCTSTR)strEndBoundary, strEndBoundary.GetLength()); pFile->Write(_T("\r\n"), 2); } CString CMyDlg::GetFileName(const CString& strPath) { int nPos = strPath.ReverseFind(_T('\\')); if (nPos != -1) { return strPath.Mid(nPos + 1); } else { return strPath; } } CString CMyDlg::FormatFileSize(ULONGLONG nFileSize) { CString strFileSize; if (nFileSize >= 1024 * 1024 * 1024) { strFileSize.Format(_T("%.2f GB"), (double)nFileSize / (1024 * 1024 * 1024)); } else if (nFileSize >= 1024 * 1024) { strFileSize.Format(_T("%.2f MB"), (double)nFileSize / (1024 * 1024)); } else if (nFileSize >= 1024) { strFileSize.Format(_T("%.2f KB"), (double)nFileSize / 1024); } else { strFileSize.Format(_T("%d bytes"), nFileSize); } return strFileSize; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值