Win32 HTTP Download
头文件HTTPClient.h:
#pragma once
#ifndef HTTPClient_H_
#define HTTPClient_H_ #include <string>
using namespace std; class HTTPClient
{
public:
HTTPClient(void);
~HTTPClient(void); bool DownloadFile(string serverName,int port,string sourcePath, string fileName, string localDirectory);
};
#endif
源文件HTTPClient.cpp:
#include "StdAfx.h"
#include "HTTPClient.h"
#include <winsock.h>
#include <fstream>
//#include "Log.h"
#pragma comment(lib,"ws2_32.lib") HTTPClient::HTTPClient(void)
{
} HTTPClient::~HTTPClient(void)
{
} bool HTTPClient::DownloadFile(string serverName,int port, string sourcePath, string fileName, string localDirectory)
{
//Log &log = Log::getLog("HTTPClient","DownloadFile");
//log.debug("\nserverName = %s; sourcePath = %s; fileName = %s\n",serverName.c_str(),sourcePath.c_str(),fileName.c_str()); WSADATA wsaData;
int nRet; //
// Initialize WinSock.dll
//
nRet = WSAStartup(0x101, &wsaData);
if (nRet)
{
//log.debug("\nWinSock.dll initialize failed. WSAStartup(): %d\n", nRet);
WSACleanup();
return false;
}
else
{
//log.debug("\nWSAStartup success!\n");
} //
// Check WinSock version
//
if (wsaData.wVersion != 0x101)
{
//log.debug("\nWinSock version not supported\n");
WSACleanup();
return false;
}
else
{
//log.debug("\nwsaData.wVersion ==0x101\n");
} ofstream fout;
string newfile = localDirectory + fileName;
fout.open(newfile.c_str(),ios_base::binary);
if(!fout.is_open())
{
//log.debug("open newfile error!");
}
else
{
//log.debug("open local newfile success!");
} IN_ADDR iaHost;
LPHOSTENT lpHostEntry; iaHost.s_addr = inet_addr(serverName.c_str());
if (iaHost.s_addr == INADDR_NONE)
{
// Wasn't an IP address string, assume it is a name
lpHostEntry = gethostbyname(serverName.c_str());
}
else
{
// It was a valid IP address string
lpHostEntry = gethostbyaddr((const char *)&iaHost,
sizeof(struct in_addr), AF_INET);
}
if (lpHostEntry == NULL)
{
//log.debug("gethostbyname() error");
return false;
}
else
{
//log.debug("gethostbyname() success!");
} //
// Create a TCP/IP stream socket
//
SOCKET Socket; Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Socket == INVALID_SOCKET)
{
//log.debug("socket() error");
return false;
}
else
{
//log.debug("socket() success!");
} //
// Find the port number for the HTTP service on TCP
//
SOCKADDR_IN saServer;
//LPSERVENT lpServEnt; //lpServEnt = getservbyname("http", "tcp");
//if (lpServEnt == NULL)
// saServer.sin_port = htons(80);
//else
// saServer.sin_port = lpServEnt->s_port; saServer.sin_port = htons(port); //
// Fill in the rest of the server address structure
//
saServer.sin_family = AF_INET;
saServer.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list); //
// Connect the socket
//
nRet = connect(Socket, (LPSOCKADDR)&saServer, sizeof(SOCKADDR_IN));
if (nRet == SOCKET_ERROR)
{
//log.debug("connect() error");
closesocket(Socket);
return false;
}
else
{
//log.debug("connect() success!");
} //
// Format the HTTP request
//
char szBuffer[]; string requestFile = sourcePath + fileName; sprintf(szBuffer, "GET %s\n", requestFile.c_str());
//log.debug("sended GET %s Request",requestFile.c_str());
nRet = send(Socket, szBuffer, strlen(szBuffer), );
if (nRet == SOCKET_ERROR)
{
//log.debug("send() error");
closesocket(Socket);
return false;
} //
// Receive the file contents and print to stdout
//
while()
{
// Wait to receive, nRet = NumberOfBytesReceived
nRet = recv(Socket, szBuffer, sizeof(szBuffer), );
if (nRet == SOCKET_ERROR)
{
//log.debug("recv() error");
break;
} //log.debug("\nrecv() returned %d bytes", nRet);
// Did the server close the connection?
if (nRet == )
break;
// Write to stdout
// fwrite(szBuffer, nRet, 1, stdout);
fout.write(szBuffer,nRet);
}
closesocket(Socket);
fout.close(); WSACleanup();
return true;
}
调用示例:
#include "stdafx.h"
#include "HTTPClient.h" int _tmain(int argc, _TCHAR* argv[])
{ HTTPClient* client;
client=new HTTPClient();
bool a = client->DownloadFile("127.0.0.1",,"/","KeyBoardSelectionComboBox.zip","c:\\");
bool b = client->DownloadFile("www.zt.cn",,"/ClientBin/","Main.xap","c:\\"); return ;
}
Win32 HTTP Download的更多相关文章
- gtk+2.24.0-glib-2.28.1-staticLib-mingw32-x86-2016-08-10.7z
GTK_PATH=D:/MSYS/opt/gtk+2.24.0-staticLib b1-static.sh --------------------------------------------- ...
- 怎样在WINDOWS下面编译LIBCURL
我测试过,好像没OK This is a short note about building cURL with SSL support on Windows. Tools required: cUR ...
- cocos2d-x 从win32到android移植的全套解决方案
引言:我们使用cocos2d-x引擎制作了一款飞行射击游戏,其中创新性地融入了手势识别功能.但是我们在移植过程中遇到了很多的问题,同时也发现网上的资料少而不全.所以在项目行将结束的时候,我们特地写了这 ...
- Serial Port Programming using Win32 API(转载)
In this tutorial we will learn How to communicate with an external device like a microcontroller boa ...
- Download the WDK, WinDbg, and associated tools
Download the WDK, WinDbg, and associated tools This is where you get your Windows Driver Kit (WDK) a ...
- 【转】VS2012编译出来的程序,在XP上运行,出现“.exe 不是有效的 win32 应用程序” “not a valid win32 application”
原文网址:http://www.cnblogs.com/Dageking/archive/2013/05/15/3079394.html VS2012编译出来的程序,在XP上运行,出现“.exe 不是 ...
- win32进阶之路:程序托盘图标+右键弹出菜单
开场白 本次介绍两个非常棒且实用的技巧:程序托盘图标和右键弹出菜单,效果如下图. 程序托盘图标用了迅雷的图标,右键点击时候会弹出三个选项的菜单. 程序托盘图标设置 我会用尽可能清晰明了的步骤介绍方式 ...
- VS2012编译出来的程序,在XP上运行,出现“.exe 不是有效的 win32 应用程序” “not a valid win32 application”
升级vs2010到vs2012,突然发现build出来的应用程序无法运行,提示“不是有效的 win32 应用程序” or “not a valid win32 application”. 参考CSDN ...
- WIN32不得不会:视频播放器
我愿分享我所有的技术,你可愿意做我的朋友? ----赵大哥 为何要写这篇博客 纯WIN32API打造,自认为对底层的理解略有帮助,和大家分享成果和知识点. 已经实现功能有:打开.播放.关闭功能. 核心 ...
随机推荐
- js程序中美元符号$是什么(转)
$符号在php中是表示变量的特征字符, 在js中它也有很多作用, 一般我们用来命名一个函数名称,获取id的1.首先可以用来表示变量, 比如变量 var s='asdsd'或var $s='asdasd ...
- R包下载的一些小问题
install.packages(c("matrixStats", "Hmisc", "splines", "foreach&qu ...
- 如何解决css-子div设置margin-top后,父div与子div一起下移的bug?
根据规范,一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边距重叠. 这是规范引起的普遍问题. 只要给父盒子设 ...
- LeetCode 544----Output Contest Matches
During the NBA playoffs, we always arrange the rather strong team to play with the rather weak team, ...
- 实现ListView的加载更多的效果,如何将按钮布局到始终在ListView的最后一行
实现方式一:在代码中实现: 1,在一个布局中定义一个Button,在活动中加载Button的父布局, 例如:View bottomView = getLayoutInflater().inflate( ...
- webapp开发绝对定位引发的问题
最近做了一个webapp 需求是要滑动页面翻页,我使用了大量绝对定位 当遇到输入框时,在部分手机上发现了问题.虚拟键盘收回时,整个body全部下移了,经过多次测试, 发现是fixed布局的音乐按钮造成 ...
- 如何查看Ext自带的API和示例
Ext是一款富客户端开发框架,它基于JavaScript.HTML和CSS开发而成,无须安装任何插件即可在常用浏览器中创建出绚丽的页面效果. 1.下载地址http://www.sencha.com/p ...
- Prometheus Node_exporter 之 Basic CPU / Mem / Disk Gauge
1. CPU Busy :收集所有 cpu 内核 busy 状态占比 type: SinglestatUnit: perent(0-100)(所有 cpu使用情况 - 5分钟内 cpu 空闲的平均值) ...
- JSP九大内置对象与Servlet的对应关系
JSP对象 Servlet中怎样获得 request service方法中的request参数 response service方法中的res ...
- 【Oracle】存储过程写法小例子
1.存储过程的基本语法: CREATE OR REPLACE PROCEDURE 存储过程名(param1 in type,param2 out type) IS 变量1 类型(值范围); 变量2 类 ...