Win32的Winnet操作:http的post、get请求、下载文件,ftp的上传、下载

  • 时间:
  • 来源:互联网
  • 文章标签:
////http的post
void testhttpPost()
{
	HINTERNET hInternet = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); //初始化WinINet
 HINTERNET hConnect = InternetConnectA(hInternet, "127.0.0.1", 8080,
  NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); //连接服务器

 HINTERNET hOpenRequest = HttpOpenRequestA(hConnect, "POST", "/xxxxx/testcheck?mobile=123456789", NULL, NULL,
  (LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1); //创建http请求
 BOOL bRequest = HttpSendRequestA(hOpenRequest, NULL, 0, NULL, 0); //发送http请求
 TCHAR szBuffer[1024] = {'\0'};
  ZeroMemory(szBuffer, 1024);  
  std::string stTemp;
  char chTemp[1024];
  ZeroMemory(chTemp, 1024);
  BYTE Temp[1024];
  ZeroMemory(Temp, 1024);
  ULONG Number = 1;
  while (Number > 0)
  {
	  InternetReadFile(hOpenRequest, Temp, 1024 - 1, &Number);
	  if (Number<=0)
	  {
		  break;
	  }
	  Temp[Number] = '\0';
	  CopyMemory(chTemp, Temp, Number);
	  //printf("%s", Temp);
	  std::wstring strRet =  ConvertUtf8ToUnicode(chTemp);
	  std::wcout.imbue(locale("chs"));  
	  std::wcout << strRet.c_str() << std::endl;
  }

}
/////////////////////http的Get请求
void testhttpGet()
{
	HINTERNET hInternet = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); //初始化WinINet
 HINTERNET hConnect = InternetConnectA(hInternet, "127.0.0.1", 8080,
  NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); //连接服务器

 HINTERNET hOpenRequest = HttpOpenRequestA(hConnect, "POST", "/XXXXXXX/testcheck?mobile=123456789", NULL, NULL,
  (LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1); //创建http请求
 BOOL bRequest = HttpSendRequestA(hOpenRequest, NULL, 0, NULL, 0); //发送http请求
 TCHAR szBuffer[1024] = {'\0'};
  ZeroMemory(szBuffer, 1024);  
  std::string stTemp;
  char chTemp[1024];
  ZeroMemory(chTemp, 1024);
  BYTE Temp[1024];
  ZeroMemory(Temp, 1024);
  ULONG Number = 1;
  while (Number > 0)
  {
	  InternetReadFile(hOpenRequest, Temp, 1024 - 1, &Number);
	  if (Number<=0)
	  {
		  break;
	  }
	  Temp[Number] = '\0';
	  CopyMemory(chTemp, Temp, Number);
	  //printf("%s", Temp);
	  std::wstring strRet =  ConvertUtf8ToUnicode(chTemp);
	  std::wcout.imbue(locale("chs"));  
	  std::wcout << strRet.c_str() << std::endl;
  }
}



/////http文件下载
bool testHttpDownload()

{

	// 建立会话

	HINTERNET hInternet;

	hInternet = InternetOpen(TEXT(""), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);

	if(hInternet == NULL)  return false;

	// 建立连接

	HINTERNET hConnect;

	hConnect = InternetConnect(hInternet, TEXT("127.0.0.1:8082"), INTERNET_INVALID_PORT_NUMBER,

		TEXT(""), TEXT(""), INTERNET_SERVICE_HTTP, INTERNET_FLAG_PASSIVE, 0);

	if( hConnect == NULL )

	{

		InternetCloseHandle(hInternet); 

		return false; 

	}

	HINTERNET httpFile;

	httpFile = HttpOpenRequest(hConnect, TEXT("GET"), TEXT("logo.png"), HTTP_VERSION, NULL, 0,        INTERNET_FLAG_NO_UI | INTERNET_FLAG_DONT_CACHE, 1);

	if(httpFile == NULL)

	{   

		InternetCloseHandle(hConnect); 

		InternetCloseHandle(hInternet); 

		return false;

	}

	HttpSendRequest(httpFile, NULL, NULL, 0, 0);

	char buf[1024];

	DWORD buf_len = 1024;

	DWORD buf_read = 1024;

	FILE *fp = fopen("update/logo.png", "wb");

	while(1)

	{

		InternetReadFile(httpFile, buf, buf_len, &buf_read);

		if(buf_read == 0) break;

		fwrite(buf, 1, buf_read, fp);

	}

	fclose(fp);



	InternetCloseHandle(httpFile);

	InternetCloseHandle(hConnect);

	InternetCloseHandle(hInternet);

	return true;

}




//ftp头文件
#pragma once

#include <queue>
#include <io.h>
#include <cstring>
#include <time.h>
 #include <sstream>

#define  FTP_FUNCTIONS_BUFFER_SIZE          MAX_PATH+8

typedef struct FileAttr
{
	DWORDLONG filesize;
	CString  filename;
	CString  filetime;
	int type;
};
class MyFtp
{
public:
	MyFtp(void);
	~MyFtp(void);

	bool Connect(CString const& username,CString const& pwd,CString const& ip, CString const& port);
	bool GetCurrentDir();
	bool GetFileList();
	bool listFiles(const char * dir);
	bool CreateTmpFile(CString filename,int type);
	bool CreateTmpDir();
	bool DeleteTmpFile(const wchar_t* path);
	bool Utf8ToUnicode( std::string& utf8_string, std::wstring& unicode_string);
	bool MyPutFile(CString file,CString filename,int type=1);
	HRESULT RemoveDir( std::wstring& wstrTargetPath )  ;
	bool MyFtpGetFile(CString file,CString filename,int type=1);
private:
	BOOL WINAPI DisplayFtpDir(HINTERNET hConnection,DWORD dwFindFlags);
public:
	HINTERNET m_hConnect;
	HINTERNET m_hInternet;
	CString m_CurrDir;
	std::queue<FileAttr> m_FileList;
    std::queue<FileAttr> m_LocalFileList;
	std::queue<FileAttr> m_RemoteFile;
	std::wstring m_FileRoot;

};



//ftp实现

#include "StdAfx.h"
#include "MyFtp.h"


BOOL StringToWString(const std::string &str,std::wstring &wstr)
{    
	int nLen = (int)str.length();    
	wstr.resize(nLen,L' ');

	int nResult = MultiByteToWideChar(CP_ACP,0,(LPCSTR)str.c_str(),nLen,(LPWSTR)wstr.c_str(),nLen);

	if (nResult == 0)
	{
		return FALSE;
	}

	return TRUE;
}
//wstring高字节不为0,返回FALSE
BOOL WStringToString(const std::wstring &wstr,std::string &str)
{    
	int nLen = (int)wstr.length();    
	str.resize(nLen,' ');

	int nResult = WideCharToMultiByte(CP_ACP,0,(LPCWSTR)wstr.c_str(),nLen,(LPSTR)str.c_str(),nLen,NULL,NULL);

	if (nResult == 0)
	{
		return FALSE;
	}

	return TRUE;
}

MyFtp::MyFtp(void)
{
	m_hConnect=NULL;
	m_hInternet=NULL;
    m_CurrDir=_T("");
	
}

MyFtp::~MyFtp(void)
{
	if (m_hConnect)
	{
		InternetCloseHandle(m_hConnect);
	}
	if (m_hInternet)
	{
		InternetCloseHandle(m_hInternet);
	}

	
	std::queue<FileAttr> empty;
	swap(empty, m_FileList);
	swap(empty, m_LocalFileList);
	m_hConnect=NULL;
	m_hInternet=NULL;
}

bool MyFtp::Connect(CString const& username,CString const& pwd,CString const& ip, CString const& port)
{
	if (m_hConnect)
	{
		InternetCloseHandle(m_hConnect);
	}
	if (m_hInternet)
	{
		InternetCloseHandle(m_hInternet);
	}
	m_hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	if(m_hInternet == NULL) 
	{
		CString str ;
		str.Format(_T("打开%s失败,错误码:%ld"),ip,GetLastError());
		AfxMessageBox(str);
		return false;
	}

	// 建立连接

	m_hConnect = InternetConnect(m_hInternet, ip, _ttoi(port),

		username, pwd, INTERNET_SERVICE_FTP, INTERNET_FLAG_EXISTING_CONNECT || INTERNET_FLAG_PASSIVE, 0);

	if( m_hConnect == NULL )

	{
		std::cout << GetLastError() << std::endl;
		CString str ;
		str.Format(_T("连接%s失败,错误码:%ld"),ip,GetLastError());
		AfxMessageBox(str);
		InternetCloseHandle(m_hInternet); 

		return false; 

	}
	return true;
}

bool MyFtp::GetCurrentDir()
{
	  DWORD len = MAX_PATH;
	  TCHAR dir[MAX_PATH] = {'\0'};
      BOOL ret = FtpGetCurrentDirectory(m_hConnect,dir,&len);
	  if(!ret)
	  {
		  CString str ;
		  str.Format(_T("获取当前文件路径失败,错误码:%ld"),GetLastError());
		  AfxMessageBox(str);
		  return false;
	  }
	  m_CurrDir = dir;
	  return true;
}
bool MyFtp::GetFileList()
{
    bool ret = DisplayFtpDir(m_hConnect,INTERNET_FLAG_RELOAD);
	if(!ret)
	{
		return false;
	}
	return true;
}
BOOL WINAPI  MyFtp::DisplayFtpDir(HINTERNET hConnection,DWORD dwFindFlags)
{
	WIN32_FIND_DATA dirInfo;
	HINTERNET       hFind;
	DWORD           dwError;
	BOOL            retVal = FALSE;
	TCHAR           szMsgBuffer[FTP_FUNCTIONS_BUFFER_SIZE];
	TCHAR           szFName[FTP_FUNCTIONS_BUFFER_SIZE];

	std::queue<FileAttr> empty;
	swap(empty, m_FileList);
	hFind = FtpFindFirstFile( hConnection, TEXT( "*.*" ), 
		&dirInfo, dwFindFlags, 0 );
	if ( hFind == NULL )
	{
		dwError = GetLastError( );
		if( dwError == ERROR_NO_MORE_FILES )
		{
			StringCchCopy( szMsgBuffer, FTP_FUNCTIONS_BUFFER_SIZE,
				TEXT( "No files found at FTP location specified." ) );
			retVal = TRUE;
			goto DisplayDirError_1;
		}
		StringCchCopy( szMsgBuffer, FTP_FUNCTIONS_BUFFER_SIZE,
			TEXT( "FtpFindFirstFile failed." ) );
		goto DisplayDirError_1;
	}

	do
	{
		if( FAILED( StringCchCopy( szFName, FTP_FUNCTIONS_BUFFER_SIZE,
			dirInfo.cFileName ) ) ||
			( ( dirInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) &&
			( FAILED( StringCchCat( szFName, FTP_FUNCTIONS_BUFFER_SIZE,
			TEXT( " <DIR> " ) ) ) ) ) )
		{
			StringCchCopy( szMsgBuffer, FTP_FUNCTIONS_BUFFER_SIZE,
				TEXT( "Failed to copy a file or directory name." ) );
			retVal = FALSE;
			goto DisplayDirError_2;
		}
		SYSTEMTIME stUTC, stLocal;
		DWORD dwRet;
		// Convert the last-write time to local time.
		FileTimeToSystemTime(&dirInfo.ftLastWriteTime, &stUTC);
		SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

		// Build a string showing the date and time.
		TCHAR szBuf[MAX_PATH]={'\0'};
		dwRet = StringCchPrintf(szBuf, MAX_PATH, 
			TEXT("%04d/%02d/%02d  %02d:%02d:%02d"),
			stLocal.wYear, stLocal.wMonth, stLocal.wDay,
			stLocal.wHour, stLocal.wMinute,stLocal.wSecond);
		if( S_OK == dwRet )
		{
			DWORDLONG FileSize = (dirInfo.nFileSizeHigh * (MAXDWORD+1)) + dirInfo.nFileSizeLow;
			FileAttr fa;
			fa.filename = szFName;
			fa.filesize = FileSize;
			fa.filetime = szBuf;
			if (dirInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{
				fa.type = 0;
			}else
			{
				fa.type = 1;
			}
			m_FileList.push(fa);
		}else
		{

		}
	  
	} while( InternetFindNextFile( hFind, (LPVOID) &dirInfo ) );

	if( ( dwError = GetLastError( ) ) == ERROR_NO_MORE_FILES )
	{
		InternetCloseHandle(hFind);
		return( TRUE );
	}
	StringCchCopy( szMsgBuffer, FTP_FUNCTIONS_BUFFER_SIZE,
		TEXT( "FtpFindNextFile failed." ) );

DisplayDirError_2:
	InternetCloseHandle( hFind );
DisplayDirError_1:
	MessageBox( NULL,
		(LPCTSTR) szMsgBuffer,
		TEXT( "DisplayFtpDir( ) Problem" ),
		MB_OK | MB_ICONERROR );
	return( retVal );
}

bool MyFtp::listFiles(const char * dir)
{
	intptr_t handle;
	_finddata_t findData;

	handle = _findfirst(dir, &findData);    // 查找目录中的第一个文件
	if (handle == -1)
	{
		std::cout << "Failed to find first file!\n";
		return false;
	}
	std::queue<FileAttr> empty;
	swap(empty, m_LocalFileList);
	FileAttr fa;
	do
	{
		if (findData.attrib & _A_SUBDIR
			&& strcmp(findData.name, ".") == 0
			&& strcmp(findData.name, "..") == 0
			)    // 是否是子目录并且不为"."或".."
		{//
          	//std::cout << findData.name << "\t<dir>\n";
			//CString str;
			//struct tm t;   //tm结构指针
			//localtime_s(&t, &findData.time_write);   //获取当地日期和时间
			//str.Format(_T("%s"),findData.name);
			//fa.filename = findData.name;
			//fa.filesize = findData.size;
			//str.Format(_T("%04d/%02d/%02d %02d:%02d:%02d"),t.tm_year+1900,t.tm_mon + 1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
			//fa.filetime = str;
			//m_LocalFileList.push(fa);
		}
		else
		{
			//std::cout << findData.name << "\t" << findData.size << endl;
			CString str;
			struct tm t;   //tm结构指针
			localtime_s(&t, &findData.time_write);   //获取当地日期和时间
			str.Format(_T("%s"),findData.name);
			fa.filename = findData.name;
			//str.Format(_T("%ld"),findData.size);
			fa.filesize = findData.size;
			str.Format(_T("%04d/%02d/%02d %02d:%02d:%02d"),t.tm_year+1900,t.tm_mon + 1,t.tm_mday,t.tm_hour,t.tm_min,t.tm_sec);
			fa.filetime = str;
			if (findData.attrib & _A_SUBDIR)
			{
				fa.type = 0;
			}else{
				fa.type = 1;
			}
			if (strcmp(findData.name, ".") == 0
				|| strcmp(findData.name, "..") == 0)
			{

			}
			else
			{
                m_LocalFileList.push(fa);
			}

		}
			
	} while (_findnext(handle, &findData) == 0);    // 查找目录中的下一个文件

	std::cout << "Done!\n";
	_findclose(handle);    // 关闭搜索句柄

	return true;
}

bool MyFtp::CreateTmpFile(CString filename,int type)
{
	std::wstring tmp = m_FileRoot;
	std::wstring seq = L"\\";
	std::wstring tmpfile = filename.GetString();
    tmp = tmp + seq+tmpfile;


   if (type==0)//文件夹
   {
	   BOOL ret = ::CreateDirectory(tmp.c_str(), NULL);
	   if(!ret){
		   //std::cout << "创建文件夹失败:" << GetLastError() << std::endl;  
		   return false;
	   }
   }else
   {
	   HANDLE hFile = ::CreateFile(tmp.c_str(),  // 在当前文件夹创建test.txt文件  
		   GENERIC_WRITE, 0, NULL,  
		   CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);  

	   if (INVALID_HANDLE_VALUE == hFile)  // 判断文件是否创建成功  
	   {  
		   return false;  
	   }  
	   CloseHandle(hFile);  
   }
   FileAttr fa;
   fa.type = type;
   fa.filename = tmp.c_str();
   m_RemoteFile.push(fa);
   return true;
}
bool MyFtp::CreateTmpDir()
{
	std::string file = "Tmp";
	std::wstring unicode_string = L"";
	bool ret1 = Utf8ToUnicode(file,unicode_string);
	if(!ret1) {
		std::cout << "string转wstring失败" << std::endl;
		return false;
	}
	m_FileRoot=unicode_string;
	if (PathIsDirectory(m_FileRoot.c_str()))//存在
	{
		//bool ret = DeleteTmpFile(m_FileRoot.c_str());
		HRESULT hRet = RemoveDir( m_FileRoot );  
		if (SUCCEEDED(hRet)) 
		{

		}
		else
		{
			AfxMessageBox(_T("删除失败"));
			return false;
		}
		
	}

	DWORD code = GetLastError();
	BOOL ret = ::CreateDirectory(m_FileRoot.c_str(), NULL);
	if(!ret){
		//std::cout << "创建文件夹失败:" << GetLastError() << std::endl;  
		return false;
	}
	return true;
}
bool MyFtp::DeleteTmpFile(const wchar_t* path)
{
	SHFILEOPSTRUCT FileOp;  
	FileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;  
	FileOp.hNameMappings = NULL;  
	FileOp.hwnd = NULL;  
	FileOp.lpszProgressTitle = NULL;  
	FileOp.pFrom = path;  
	FileOp.pTo = NULL;  
	FileOp.wFunc = FO_DELETE;  
	return SHFileOperation(&FileOp);  
}

bool MyFtp::Utf8ToUnicode( std::string& utf8_string, std::wstring& unicode_string)
{
	unicode_string = L"";
	if (utf8_string.compare("") == 0 )
	{
		return false;
	}

	const char *temp_utf8_string = utf8_string.c_str();
	int unicode_string_len = ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), NULL, 0);
	if (0 == unicode_string_len )
	{
		return false;
	}

	wchar_t *temp_unicode_string = new wchar_t[unicode_string_len + 1];
	memset(temp_unicode_string, 0, sizeof(wchar_t) * (unicode_string_len + 1));
	if (0 == ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), temp_unicode_string, unicode_string_len))
	{
		delete[] temp_unicode_string;
		temp_unicode_string = NULL;
		return false;
	}

	unicode_string = temp_unicode_string;
	delete[] temp_unicode_string;
	temp_unicode_string = NULL;

	return true;

}

HRESULT MyFtp::RemoveDir( std::wstring& wstrTargetPath )  
{  
    if (wstrTargetPath.empty() || wstrTargetPath.length() > MAX_PATH)  
    {  
        return E_INVALIDARG;  
    }  
  
    /* 
    * 元素全部初始化为 '/0',保证结尾至少有两个 '/0' 
    */  
    WCHAR   pwszTargetPath[MAX_PATH + 1]    = {0};  
  
    ::wcsncpy_s(  
        pwszTargetPath,  
        _countof(pwszTargetPath),  
        wstrTargetPath.c_str(),  
        wstrTargetPath.length()  
        );  
  
    SHFILEOPSTRUCTW FileOp =      
    {     
        NULL,  
        FO_DELETE,  
        pwszTargetPath,  
        NULL,  
        FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMATION,  
        FALSE,  
        NULL,  
        NULL  
    };     
  
    int nRet = ::SHFileOperationW(&FileOp);  
  
    return HRESULT_FROM_WIN32(nRet);  
}  
bool MyFtp::MyPutFile(CString file,CString filename,int type)
{
  if (type==1)
  {
	  
       BOOL ret = FtpPutFile(m_hConnect, file, filename, FTP_TRANSFER_TYPE_BINARY, 0);
	   if (!ret)
	   {
		   return false;
	   }
  }

  return true;

}

bool  MyFtp::MyFtpGetFile(CString file,CString filename,int type)
{

	if (type==1)
	{
	
		BOOL ret = FtpGetFile(m_hConnect, filename, file, FALSE,FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY, 1);
		if (!ret)
		{
			CString str;
			str.Format(_T("错误码:%ld"),GetLastError());
			AfxMessageBox(str);
			return false;
		}
	}

	return true;
}




本文链接http://www.taodudu.cc/news/show-647620.html