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[1024];
 
    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), 0);
    if (nRet == SOCKET_ERROR)
    {
        //log.debug("send() error");
        closesocket(Socket);   
        return false;
    }
 
    //
    // Receive the file contents and print to stdout
    //
    while(1)
    {
        // Wait to receive, nRet = NumberOfBytesReceived
        nRet = recv(Socket, szBuffer, sizeof(szBuffer), 0);
        if (nRet == SOCKET_ERROR)
        {
            //log.debug("recv() error");
            break;
        }
 
        //log.debug("\nrecv() returned %d bytes", nRet);
        // Did the server close the connection?
        if (nRet == 0)
            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",80,"/","KeyBoardSelectionComboBox.zip","c:\\");
    bool b = client->DownloadFile("www.zt.cn",88,"/ClientBin/","Main.xap","c:\\");
     
    return 0;
}

  

posted on   chuncn  阅读(1749)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端

导航

< 2012年3月 >
26 27 28 29 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
1 2 3 4 5 6 7
点击右上角即可分享
微信分享提示