#include "afxwin.h"
#include "afxinet.h"
#include <string>
CString CTicketCheckSysDlg::HttpPostMessage( CString strUrl, CString strPostDate )
{
CString strJsonMessage(_T("-1"));
CString strServer;
CString strObject;
DWORD dwServiceType;
INTERNET_PORT nPort;
AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort);
using namespace std;
CInternetSession session;
try
{
DWORD dwRet = 0;
BOOL bRet = session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_CONTROL_SEND_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_LISTEN_TIMEOUT, 5000);
bRet = session.SetOption(INTERNET_OPTION_FROM_CACHE_TIMEOUT, 5000);
CHttpConnection* pServer = session.GetHttpConnection(strServer, nPort);
CHttpFile* pHttpFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
CString strHeaders = _T("Content-Type: application/json; charset=utf-8"); // 请求头
//开始发送请求
std::string strTmpDate;
char * lp = NULL;
CCodingConv codingconvert;// 在上一篇文章中查看类定义
int nretLen = codingconvert.ConvertStringToUTF8(strPostDate, lp);
BOOL bSendRequest = pHttpFile->SendRequest(strHeaders,lp,nretLen);
delete []lp;
lp = NULL;
if (!bRet || !bSendRequest)
{
//发送请求失败
return strJsonMessage;
}
pHttpFile->QueryInfoStatusCode(dwRet);
if (dwRet == HTTP_STATUS_OK) // 请求数据成功
{
char szChars[BUFFER_SIZE + 1] = {0};
string strRawResponse = "";
UINT nReaded = 0;
while ((nReaded = pHttpFile->Read((void*)szChars, BUFFER_SIZE)) > 0)
{
szChars[nReaded] = '\0';
strRawResponse += szChars;
memset(szChars, 0, BUFFER_SIZE + 1);
}
int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, strRawResponse.c_str(), -1, NULL, 0);
WCHAR *pUnicode = new WCHAR[unicodeLen + 1];
memset(pUnicode,0,(unicodeLen+1)*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8,0,strRawResponse.c_str(),-1, pUnicode,unicodeLen);
CString strTemp(pUnicode);
strJsonMessage = strTemp;
delete []pUnicode;
pUnicode = NULL;
}
else
{
return strJsonMessage;
}
delete pHttpFile;
delete pServer;
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
TCHAR pszError[200];
pEx->GetErrorMessage(pszError, 200);
return strJsonMessage;
}
BOOL bRet = session.SetOption(INTERNET_OPTION_DISCONNECTED_TIMEOUT, 5000);
session.Close();
return strJsonMessage;
}
MFC访问http协议
最新推荐文章于 2024-05-28 10:15:33 发布