MFC HTTP 上传下载

比较简单的是文件下载,这个很简单,所以直接把程序贴出来

1--添加头文件和lib

#include <afxinet.h>

#include "afxwin.h"

#pragma comment(lib,"Wininet.lib")

#define  __BUFFER_SIZE 1024

 

2--文件下载:

BOOL CHTCodeServerSYSDlg::DownLoadFile(LPCTSTR szRemoteURI, LPCTSTR szLocalPath)

{

ASSERT(NULL != szRemoteURI && NULL != szLocalPath);

CInternetSession session;

CHttpConnection* pHttpConnection = NULL;

CHttpFile* pHttpFile = NULL;

CString strServer = _T(""), strObject = _T("");

INTERNET_PORT wPort = 0;

DWORD dwType = 0;

DWORD dwFlag = 0;

HANDLE hFile = NULL;

TCHAR  pszBuffer[__BUFFER_SIZE];

DWORD  dwFileSize = 0;

const int nTimeOut = 2000;

session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);

session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);

BOOL bResult = FALSE;

try

{

//用二进制形势传输,不使用缓存,强制重载数据

//如果没有设置这个标志那么每次从服务器下载的文件会都一样,就算服务器上的文件变了,也还一样

//原因就是缓存问题,所以设置这个标志就能防止那种坑爹问题

dwFlag = INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD;

AfxParseURL(szRemoteURI, dwType, strServer, strObject, wPort);

pHttpConnection = session.GetHttpConnection(strServer, wPort, NULL, NULL);

ASSERT(NULL != pHttpConnection);

pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwFlag);

ASSERT(NULL != pHttpFile);

if (!pHttpFile->SendRequest())

goto _err_handler;

 

//INTERNET_FLAG_RELOAD

 

DWORD dwStateCode;

pHttpFile->QueryInfoStatusCode(dwStateCode);

if (dwStateCode != HTTP_STATUS_OK)

goto _err_handler;

hFile = CreateFile(szLocalPath, GENERIC_WRITE,

FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile == INVALID_HANDLE_VALUE)

{

DWORD reterr = GetLastError();

goto _err_handler;

 

}

 

BOOL bRet = pHttpFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, dwFileSize);

if (!bRet)

goto _err_handler;

 

DWORD dwWrite = 0, dwTotalWrite = 0;

UINT nRead = 0;

do

{

nRead = pHttpFile->Read(pszBuffer, __BUFFER_SIZE);

if (nRead <= 0) break;

WriteFile(hFile, pszBuffer, nRead, &dwWrite, NULL);

ASSERT(nRead == dwWrite);

dwTotalWrite += dwWrite;

} while (TRUE);

if (dwTotalWrite != dwFileSize)

goto _err_handler;

bResult = TRUE;

}

catch (CFileException* e)

{

e->Delete();

//REPORT_CACHED_EXCEPTION(_T("CFileException"));

}

catch (CInternetException* e)

{

CString sError;

sError.Format(_T("Inernet connection error : %d"), e->m_dwError);

e->Delete();

//REPORT_CACHED_EXCEPTION(sError);

}

_err_handler:

if (pHttpFile)

{

pHttpFile->Close();

delete pHttpFile;

}

if (pHttpConnection)

{

pHttpConnection->Close();

delete pHttpConnection;

}

session.Close();

if (hFile) CloseHandle(hFile);

return bResult;

}

 

3--文件上传

要注意,文件上传的调用格式,另外服务器那边也要有一个php文件来接收上传的文件,因为我是基于php的平台,

而且只能上传小于1M的文件

BOOL CHTScannerMenageSYSDlg::UploadFile(LPCTSTR szRemoteURI, LPCTSTR szLocalPath)

{

ASSERT(NULL != szRemoteURI && NULL != szLocalPath);

BOOL bResult = FALSE;

DWORD dwType = 0;

CString sServer = _T("");

CString sObject = _T("");

INTERNET_PORT wPort = 0;

DWORD dwPostSize = 0;

const int nTimeOut = 5000;

CHttpConnection* pHttpConn = NULL;

CHttpFile*       pHttpFile = NULL;

CInternetSession cis(_T("MYyyh"));

INTERNET_BUFFERS BufferIn;

DWORD dwTotalWritten = 0;

BYTE  pFileBuffer[__BUFFER_SIZE];

//DWORD dwPostSize = 0;

CFile file;

BOOL  bRet = FALSE;

bResult = AfxParseURL(szRemoteURI, dwType, sServer, sObject, wPort);

if (!bResult)

return FALSE;

bResult = FALSE;

try

{

cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);

cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);

pHttpConn = cis.GetHttpConnection(sServer, wPort, NULL, NULL);

ASSERT(NULL != pHttpConn);

pHttpFile = pHttpConn->OpenRequest(CHttpConnection::HTTP_VERB_POST, sObject);

ASSERT(NULL != pHttpFile);

bRet = file.Open(szLocalPath, CFile::shareDenyNone | CFile::modeRead);

if (!bRet)

return FALSE;

dwPostSize = (DWORD)file.GetLength();

ASSERT(dwPostSize >= 0 && dwPostSize < 0x80000000);

memset(&BufferIn, 0, sizeof(BufferIn));

BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS); // Must be set or error will occur

BufferIn.Next = NULL;

BufferIn.lpcszHeader = NULL;

BufferIn.dwHeadersLength = 0;

BufferIn.dwHeadersTotal = 0;

BufferIn.lpvBuffer = NULL;

BufferIn.dwBufferLength = 0;

BufferIn.dwBufferTotal = dwPostSize; // This is the only member used other than dwStructSize

BufferIn.dwOffsetLow = 0;

BufferIn.dwOffsetHigh = 0;

if (!pHttpFile->SendRequestEx(&BufferIn, NULL, HSR_INITIATE, 1))

{

TRACE1("Error on HttpSendRequestEx %d\n", GetLastError());

return FALSE;

}

file.SeekToBegin();

do

{

int nActual = file.Read(pFileBuffer, __BUFFER_SIZE);

if (nActual <= 0) break;

pHttpFile->Write(pFileBuffer, nActual);

dwTotalWritten += nActual;

} while (TRUE);

if (dwTotalWritten != dwPostSize)

{

file.Close();

TRACE1("\nError on InternetWriteFile %lu \n", GetLastError());

return FALSE;

}

if (!pHttpFile->EndRequest(0, NULL, 1))

{

file.Close();

TRACE1("Error on HttpEndRequest %lu \n", GetLastError());

return FALSE;

}

 

file.Close();

 

DWORD dwStateCode = 0;

pHttpFile->QueryInfoStatusCode(dwStateCode);

if (dwStateCode == HTTP_STATUS_CREATED || dwStateCode == HTTP_STATUS_OK)

bResult = TRUE;

}

catch (CFileException* e)

{

e->Delete();

//REPORT_CACHED_EXCEPTION(_T("CFileException"));

}

catch (CInternetException* e)

{

e->Delete();

CString sError;

sError.Format(_T("Inernet connection error : %d"), e->m_dwError);

//REPORT_CACHED_EXCEPTION(sError);

}

if (pHttpFile)

{

pHttpFile->Close();

delete pHttpFile;

}

if (pHttpConn)

{

pHttpConn->Close();

delete pHttpConn;

}

cis.Close();

return bResult;

}

服务端的脚本:

<!DOCTYPE html>

<html>

<body>

<?php

$myfile = "dfsgetco.dll";

//php://input表示获取传上来的数据,不过有大小限制,似乎是1M以下

$post = file_get_contents("php://input");

file_put_contents( $myfile, $post);

 

?>

</body>

</html>

 

调用程序:

//上传

void CHTScannerMenageSYSDlg::OnBnClickedButton20()

{

// TODO:  在此添加控件通知处理程序代码

//upget.php服务器上要处理数据的脚本的名称

CString szUrl = TEXT("你服务器的地址/w3ctest/upget.php");

UploadFile(szUrl, _T("D:\\Topicddd.dll"));

 

}

 

//下载

void CHTScannerMenageSYSDlg::OnBnClickedButton21()

{

// TODO:  在此添加控件通知处理程序代码

CString szUrl = TEXT("服务器的地址/w3ctest/httptest/Topicx.dll");

DownLoadFile(szUrl, _T("D:\\Topicx.ini"));

}

//测试连接:

BOOL CHTScannerMenageSYSDlg::CanWebsiteVisit(CString sURI)

{

CHttpConnection* pHttpConn = NULL;

CHttpFile* pHttpFile = NULL;

CInternetSession cis;

BOOL bResult = FALSE;

BOOL bRetVal = FALSE;

DWORD dwType = 0;

DWORD dwStateCode = 0;

INTERNET_PORT wPort = 0;

CString sServer = _T("");

CString sObject = _T("");

const int nTimeOut = 5000;

try

{

bResult = AfxParseURL(sURI, dwType, sServer, sObject, wPort);

if (!bResult)

return FALSE;

cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);

cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);

pHttpConn = cis.GetHttpConnection(sServer, wPort);

 

if (pHttpConn)

{

pHttpFile = pHttpConn->OpenRequest(CHttpConnection::HTTP_VERB_GET, sObject);

if (pHttpFile->SendRequest())

{

pHttpFile->QueryInfoStatusCode(dwStateCode);

if (dwStateCode == HTTP_STATUS_CREATED || dwStateCode == HTTP_STATUS_OK)

bRetVal = TRUE;

}

}

}

catch (CInternetException* e)

{

e->Delete();

}

catch (...)

{

}

if (pHttpFile)

{

pHttpFile->Close();

delete pHttpFile;

}

if (pHttpConn)

{

pHttpConn->Close();

delete pHttpConn;

}

cis.Close();

return bRetVal;

}

 

//附加:删除文件

BOOL CHTScannerMenageSYSDlg::DeleteFile(LPCTSTR szRemoteURI)

{

ASSERT(NULL != szRemoteURI);

CInternetSession session;

CHttpConnection* pHttpConnection = NULL;

CHttpFile* pHttpFile = NULL;

CString strServer = _T(""), strObject = _T("");

INTERNET_PORT wPort = 0;

DWORD dwType = 0;

const int nTimeOut = 2000;

session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);

session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);

BOOL bResult = FALSE;

try

{

AfxParseURL(szRemoteURI, dwType, strServer, strObject, wPort);

pHttpConnection = session.GetHttpConnection(strServer, wPort, NULL, NULL);

ASSERT(NULL != pHttpConnection);

pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_DELETE, strObject);

ASSERT(NULL != pHttpFile);

if (!pHttpFile->SendRequest())

goto _err_handler;

DWORD dwStateCode;

pHttpFile->QueryInfoStatusCode(dwStateCode);

if (dwStateCode != HTTP_STATUS_OK)

goto _err_handler;

bResult = TRUE;

}

catch (CFileException* e)

{

e->Delete();

//REPORT_CACHED_EXCEPTION(_T("CFileException"));

}

catch (CInternetException* e)

{

CString sError;

sError.Format(_T("Inernet connection error : %d"), e->m_dwError);

//REPORT_CACHED_EXCEPTION(sError);

}

_err_handler:

if (pHttpFile)

{

pHttpFile->Close();

delete pHttpFile;

}

if (pHttpConnection)

{

pHttpConnection->Close();

delete pHttpConnection;

}

session.Close();

return bResult;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值