3,055
社区成员
发帖
与我相关
我的任务
分享
bool PostHttpPage(const std::string& hostName, const std::string& pathName)
{
using namespace std;
CInternetSession session("PostFile");
CFile f;
void *pBuffer=NULL;
try
{
INTERNET_PORT nPort = 80;
DWORD dwRet = 0;
CHttpConnection* pServer = session.GetHttpConnection(hostName.c_str(), nPort); //跟服务器连接,指定80端口
CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, pathName.c_str()); //post方式打开请求
CString HeadPost("Content-Type:multipart/form-data;boundary=ZnAAAAAAAAAAGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC\r\n");
CString FilePost("Content-Disposition: form-data;name=\"test.jpg\"; filename=\"C:\\test.jpg\"\r\n\r\n");
FilePost+="Content-Type: image/pjpeg\r\n";
FilePost+="Content-Transfer-Encoding:binary\r\n";
pFile->AddRequestHeaders(HeadPost); //增加到请求头
CString PreBoundaryPost("--ZnAAAAAAAAAAGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC\r\n");
CString LastBoundaryPost("--ZnAAAAAAAAAAGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC--\r\n");
//读取文件
if (FALSE == f.Open("C:\\test.jpg", CFile::modeRead | CFile::shareDenyNone))
{
MessageBox(NULL,"Unable to open the file.","Text",MB_OK);
return FALSE;
}
int gloLen=HeadPost.GetLength()+PreBoundaryPost.GetLength()+FilePost.GetLength()+f.GetLength()+LastBoundaryPost.GetLength();
pFile->SendRequestEx(gloLen,HSR_SYNC | HSR_INITIATE); //发送数据的大小
CFile f1;
f1.Open("C:\\2.dat",CFile::modeCreate |CFile::modeWrite);
f1.Write(HeadPost,HeadPost.GetLength());
pFile->Write((LPSTR)(LPCSTR)HeadPost,HeadPost.GetLength()); //写入请求头,包括boundary的格式
f1.Write(PreBoundaryPost,PreBoundaryPost.GetLength());
pFile->Write((LPSTR)(LPCSTR)PreBoundaryPost,PreBoundaryPost.GetLength()); //写入前边界
f1.Write(FilePost,FilePost.GetLength());
pFile->Write((LPSTR)(LPCSTR)FilePost,FilePost.GetLength()); //写入文件信息
//写入文件内容
DWORD dwReadLength = -1;
pBuffer=malloc(64*10240);
while (0 != dwReadLength)
{
dwReadLength = f.Read(pBuffer, f.GetLength());
if (0 != dwReadLength)
{
pFile->Write(pBuffer, dwReadLength);
}
}
f1.Write(pBuffer, f.GetLength());
pFile->Write((LPSTR)(LPCSTR)LastBoundaryPost,LastBoundaryPost.GetLength()); //写入后边界
f1.Write(LastBoundaryPost,LastBoundaryPost.GetLength());
f1.Close();
pFile->EndRequest(HSR_SYNC);
DWORD dwResponseLength = pFile->GetLength();
LPSTR szResponse=NULL;
CString strResponse("");
while (0 != dwResponseLength)
{
szResponse = (LPSTR)malloc(dwResponseLength + 1);
szResponse[dwResponseLength] = '\0';
pFile->Read(szResponse, dwResponseLength);
strResponse += szResponse;
free(szResponse);
dwResponseLength = pFile->GetLength();
}
MessageBox(NULL,strResponse,"网页应答数据",MB_OK);
}
catch (CInternetException* pEx)
{
f.Close();
//catch errors from WinInet
TCHAR pszError[200];
pEx->GetErrorMessage(pszError,200);
std::cout<<pszError<<std::endl;//显示异常信息
if(pBuffer!=NULL)
free(pBuffer);
return false;
}
session.Close();
f.Close();
if(pBuffer!=NULL)
free(pBuffer);
return true;
}