CPP-网络/通信:POST

BOOL PostSubmit(CString strUrl,const CString&strPara, CString&strContent)
{
BOOL bRet=FALSE;

CString strInfo;

try
{
CString strServer, strObject, strHeader, strRet;
unsigned short nPort;
DWORD dwServiceType;

strInfo.Format("strUrl is %s\n",strUrl);
printf("strUrl is %s\n",strUrl);

strInfo.Format("strPara is %s\n",strPara);
printf("strPara is %s\n",strPara);

if(!AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort))//不是有效有网络地址!
{
g_DebugMsg.Sprintf("不是有效有网络地址!\n");

return FALSE;
}

strInfo.Format("dwServiceType:%d\n",dwServiceType);
printf("dwServiceType:%d\n",dwServiceType);

strInfo.Format("strServer:%s\n",strServer);
printf("strServer:%s\n",strServer);

strInfo.Format("strObject:%s\n",strObject);
printf("strObject:%s\n",strObject);

strInfo.Format("nPort:%d\n",nPort);
printf("nPort:%d\n",nPort);

CInternetSession sess(_T("faxsms"));

CHttpFile* pFile= NULL;

CHttpConnection *pServer= sess.GetHttpConnection(strServer, nPort);
if(pServer== NULL)//连接服务器失败!
{
strInfo.Format("%s\n","连接服务器失败!");
g_DebugMsg.Sprintf("连接服务器失败!\n");

return FALSE;
}

pFile= pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,strObject,NULL,1,NULL,NULL,INTERNET_FLAG_EXISTING_CONNECT);
if(pFile== NULL)//找不到网络地址
{
g_DebugMsg.Sprintf("找不到网络地址!\n");

sess.Close();
return FALSE;
}

pFile-> AddRequestHeaders("Content-Type: application/x-www-form-urlencoded");

// pFile-> AddRequestHeaders("Content-Type: HappiGo/Process");

// pFile-> AddRequestHeaders("Accept: */*");

if (!pFile->SendRequest(NULL,0,(LPTSTR)(LPCTSTR)strPara, strPara.GetLength()))
{
g_DebugMsg.Sprintf("SendRequest error!\n");

pFile->Close();
sess.Close();

return FALSE;
}

CString strSentence;
DWORD dwStatus;
DWORD dwBuffLen=sizeof(dwStatus);
BOOL bSuccess= pFile->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,&dwStatus,&dwBuffLen);

//if( bSuccess&& dwStatus>=200&& dwStatus<300)
if( bSuccess&& dwStatus==200)
{
strInfo.Format("dwStatus:%d\n",dwStatus);
printf("dwStatus:%d\n",dwStatus);

char buffer[2049];
memset(buffer,0,2049);

int nReadCount=0;

while((nReadCount= pFile->Read(buffer,2048))>0)
{
strContent+= buffer;
memset(buffer,0,2049);
}

//strInfo.Format("strContent:%s\n",strContent);
//g_DebugMsg.Sprintf("return Content :%s\n",strContent);
bRet=TRUE;
}
else//错误
{
if (bSuccess&& dwStatus>200 && dwStatus<300)
{
char buffer[2049];
memset(buffer,0,2049);

int nReadCount=0;

while((nReadCount= pFile->Read(buffer,2048))>0)
{
strContent+= buffer;
memset(buffer,0,2049);
}

strInfo.Format("strContent:%s\n",strContent);
g_DebugMsg.Sprintf("return Content :%s\n",strContent);
}

bRet=FALSE;
}

pFile->Close();
sess.Close();

}
catch (CInternetException *e)
{
g_DebugMsg.Sprintf("ERROR001 :error code is %ld\n",e->m_dwError);

bRet=FALSE;

}
catch (...)
{
g_DebugMsg.Sprintf("Unknown Error\n");

bRet=FALSE;
}

return bRet;
}

posted @ 2013-08-29 17:00  CPYER  阅读(384)  评论(0编辑  收藏  举报