18,356
社区成员
发帖
与我相关
我的任务
分享
CString strUrl = _T("http://www.baidu.com/");
LPCTSTR strAgent=_T("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1024; .NET CLR 2.0.50727)");
CInternetSession *m_pSession= new CInternetSession(strAgent); ;
CHttpConnection *m_pConnection;
CHttpFile *m_pFile;
AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort);
if (AFX_INET_SERVICE_HTTP != dwServiceType && AFX_INET_SERVICE_HTTPS != dwServiceType)
{
return FAILURE;
}
try
{
m_pConnection = m_pSession->GetHttpConnection(strServer,
dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_CONNECT : SECURE_CONNECT,
nPort);
m_pFile = m_pConnection->OpenRequest(strMethod, strObject,
NULL, 1, NULL, NULL,
(dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_REQUEST : SECURE_REQUEST));
/*设置请求相关参数*/
m_pFile->AddRequestHeaders(L"Accept: */*,application/json\r\n");//accept请求报头域,表示客户端接受哪些类型的信息
m_pFile->AddRequestHeaders(L"Accept-Charset:UTF8\r\n");
m_pFile->AddRequestHeaders(L"Accept-Language: zh-cn;q=0.8,en;q=0.6,ja;q=0.4\r\n");
m_pFile->AddRequestHeaders(L"Content-Type:application/json\r\n");//content为实体报头域,格式及编码
//m_pFile->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)strPostData, strPostData == NULL ? 0 : _tcslen(strPostData));
/*请求body内容先转为UTF-8编码,与服务端保持一致,cword为要发送内容*/
char*cword; //ANSI指针
if (strPostData != NULL){
DWORD num = WideCharToMultiByte(CP_UTF8, 0, strPostData, -1, NULL, 0, NULL, NULL);//計算這個UNICODE实际由几个UTF-8字組成
cword = (char*)calloc(num, sizeof(char)); //申请空间
if (cword == NULL) //是否申请
{
free(cword);
}
memset(cword, 0, num*sizeof(char)); //初始化
WideCharToMultiByte(CP_UTF8, 0, strPostData, -1, cword, num, NULL, NULL);
printf("content长度为%d\n", strlen(cword));
m_pFile->SendRequest(NULL, 0, cword, strlen(cword));//发送请求
}
else{
m_pFile->SendRequest(NULL, 0, NULL, 0);//发送请求
}