头文件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的更多相关文章

  1. 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 --------------------------------------------- ...

  2. 怎样在WINDOWS下面编译LIBCURL

    我测试过,好像没OK This is a short note about building cURL with SSL support on Windows. Tools required: cUR ...

  3. cocos2d-x 从win32到android移植的全套解决方案

    引言:我们使用cocos2d-x引擎制作了一款飞行射击游戏,其中创新性地融入了手势识别功能.但是我们在移植过程中遇到了很多的问题,同时也发现网上的资料少而不全.所以在项目行将结束的时候,我们特地写了这 ...

  4. Serial Port Programming using Win32 API(转载)

    In this tutorial we will learn How to communicate with an external device like a microcontroller boa ...

  5. 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 ...

  6. 【转】VS2012编译出来的程序,在XP上运行,出现“.exe 不是有效的 win32 应用程序” “not a valid win32 application”

    原文网址:http://www.cnblogs.com/Dageking/archive/2013/05/15/3079394.html VS2012编译出来的程序,在XP上运行,出现“.exe 不是 ...

  7. win32进阶之路:程序托盘图标+右键弹出菜单

     开场白 本次介绍两个非常棒且实用的技巧:程序托盘图标和右键弹出菜单,效果如下图. 程序托盘图标用了迅雷的图标,右键点击时候会弹出三个选项的菜单. 程序托盘图标设置 我会用尽可能清晰明了的步骤介绍方式 ...

  8. VS2012编译出来的程序,在XP上运行,出现“.exe 不是有效的 win32 应用程序” “not a valid win32 application”

    升级vs2010到vs2012,突然发现build出来的应用程序无法运行,提示“不是有效的 win32 应用程序” or “not a valid win32 application”. 参考CSDN ...

  9. WIN32不得不会:视频播放器

    我愿分享我所有的技术,你可愿意做我的朋友? ----赵大哥 为何要写这篇博客 纯WIN32API打造,自认为对底层的理解略有帮助,和大家分享成果和知识点. 已经实现功能有:打开.播放.关闭功能. 核心 ...

随机推荐

  1. 纠错帖:Zuul & Spring Cloud Gateway & Linkerd性能对比 (转载)

    纠错帖:Zuul & Spring Cloud Gateway & Linkerd性能对比  Spring Cloud  Spring Cloud Spring Cloud Gatew ...

  2. css/jq--弹窗写法介绍,jq插件介绍

    //html文件 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  3. jquery3.0移除了.load()方法

    参考链接:新版jquery去掉load事件了吗? 今天也遇到了这个问题,查了一下文档,确实从3.0开始移除了load.unload.error事件方法.不过依然可以用on方法绑定这些事件. Break ...

  4. 实用的Javascript获取网页屏幕可见区域高度

    本文转载原地址:这里 document.body.clientWidth ==> BODY对象宽度 document.body.clientHeight ==> BODY对象高度 docu ...

  5. CSS选择器之基本选择器+属性选择器

    1.1      id选择器 #main{ font-size:12px; margin:0; padding:0; } 其中的#main就是id选择器,用于选择HTML页面中id = "m ...

  6. Hadoop总结

    背景 Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用户可以在不了解分布式底层细节的情况下,开发分布式程序.充分利用集群的威力进行高速运算和存储. Mapreduce1 vs YA ...

  7. java 内存分析之方法返回值及匿名对象一

    package Demo; public class Point { private double x, y, z; public Point(double _x, double _y, double ...

  8. Django之modelform修改数据库

    工程包目录:https://github.com/kongzhagen/python/tree/master/Django 目的: 客户信息表Customer在前端以表单形式展示 提交Customer ...

  9. Oracle 查询状态 自检

    Tips:fnd_lobs表会保存我们上传的一些文件和Form界面“文件“-“导出”的文件.如果不定期清理了话,会出现文件上传失败,或者是导出按钮可以点击,但是点击完以后没有任何反应.这个时候我们应该 ...

  10. JQuery 常用命令总结

    下面介绍在jQuery中设置form表单中action的值的方法. $("#myFormId").attr("action", "userinfo.s ...