Click here to Skip to main content
Click here to Skip to main content

WWW (HTTP/HTTPS/FTP) Client using WININET

By , 3 May 2004
 

Introduction

This class is used for HTTP/HTTPS request, and FTP request.

Supported methods are:

  • HTTP/HTTPS
    1. GET
    2. POST
    3. POST multiparts/form-data
  • FTP
    1. GET FILE
    2. PUT FILE

Class Overview

// synchronized www client
 class W3Client {
 public:
  enum w3t { w3ftp, w3http, w3https };
  enum w3m { reqGet, reqPost, reqPostMultipartsFormdata };
 public:
  W3Client(){ _hOpen=NULL; _hConnection=NULL, _hRequest=NULL; }
  virtual ~W3Client(){ InitializePostArguments(); InitializeCookies();}
 public:  
  // connection handling
  bool Connect(const char *szaddress,
         const char *szuser=NULL, const char *szpassword=NULL, 
      const char *szagent=__W3_DEFAULT_AGENT);
  virtual bool Connect(const char *szaddress, long nport,
           const char *szuser=NULL, const char *szpassword=NULL,
           w3t t=w3http, const char *szagent=__W3_DEFAULT_AGENT);
  const char *GetURI(){ return _szuri.c_str(); }
  void Close();

  // post argument handling
  void InitializePostArguments();
  void AddPostArgument(const char *szname, const int nvalue);
  void AddPostArgument(const char *szname, const long nvalue);
  void AddPostArgument(const char *szname, const float nvalue);
  void AddPostArgument(const char *szname, const double nvalue);
  void AddPostArgument(const char *szname, 
                      const char *szvalue, bool bfile=false);
  
  // cookie handling
  void InitializeCookies();
  void AddCookie(const char *szname, const double value);
  void AddCookie(const char *szname, const float value);
  void AddCookie(const char *szname, const long value);
  void AddCookie(const char *szname, const int value);  
  void AddCookie(const char *szname, const char *szvalue);
 
  // http/https request handling
  bool Request(const char *szuri, w3m m=reqGet, const char *szref=NULL);
  unsigned long Response(unsigned char *buf, unsigned long len);
  unsigned int QueryResult();
  const char * QueryContentType();
  unsigned long QueryContentLength();
  unsigned long QueryCookie(unsigned char *buf, 
          unsigned long len, unsigned long idx=0);
  unsigned long QueryRawHeader(unsigned char *buf, unsigned long len);
 
  // ftp handling
  bool PutFile(const char *szuri, const char *szfile, bool ascii=false);
  bool GetFile(const char *szuri, const char *szfile, bool ascii=false);
  unsigned long PutFile(const char *szuri, unsigned char *buf, 
                        unsigned long len, bool ascii=false);
  unsigned long GetFile(const char *szuri, unsigned char *buf, 
                        unsigned long len, bool ascii=false);

 ...
 };

 // Asynchronized www client
 class AsyncW3Client : public W3Client {
 ...
 public:
  bool Connect(const char *szaddress,
            INTERNET_STATUS_CALLBACK lpfn,
            const char *szuser=NULL,
            const char *szpassword=NULL,
            const char *szagent=__W3_DEFAULT_AGENT);
  bool Connect(const char *szaddress, long nport,
          INTERNET_STATUS_CALLBACK lpfn,
          const char *szuser=NULL, const char *szpassword=NULL,
          w3t t=w3http, const char *szagent=__W3_DEFAULT_AGENT);
  bool Request(const char *szuri, w3m m=reqGet, const char *szref=NULL){
       _hCompleteRequestEvent=::CreateEvent(NULL, FALSE, FALSE, NULL);
       return W3Client::Request(szuri, m, szref);
  }
  unsigned long Response(unsigned char *buf, unsigned long len){
   ::CloseHandle(_hCompleteRequestEvent);
   _hCompleteRequestEvent=NULL;
   return W3Client::Response(buf, len);
  }
 public:
  void SetCompleteRequest();
  bool WaitCompleteRequest(unsigned long ntime=INFINITE);
 ...
 };
  1. Synchronized W3Client

    • Connect(...) method connects to HTTP server.
    • Close() method closes connection. These are used with RequestOfURI(...).
    • InitializePostArguments() method initializes POST arguments.
    • AddPostArgument(...) method is supported so that you can add new POST arguments of the following types: string, int, long, float, double, file.
    • Request(...) method is for you to attempt request for HTTP Request (GET, POST, POST-MULTIPARTFORMDATA) with URL. HTTP METHOD indirector has 3 types.
    • InitializeCookies() method initializes cookie values.
    • AddCookie(...) method adds cookie vars.
      • W3Client::reqGet is HTTP GET Request.
      • W3Cient::reqPost is HTTP POST Request.
      • W3Client::reqPostMultiPartsFormData is HTTP POST Request with BINARY FORM DATA.
    • Response(...) method is that you have HTTP Response by bytes.
    • QueryResult() method is you have receive HTTP Request result value.
  2. Asynchronized W3Client

    • SetCompleteRequest() method commits complete Request to AsyncW3Client.
    • WaitCompleteRequest() method waits for Request to be completed.

Usage

  1. Synchronized HTTP GET

    #include <iostream>
    #include "w3c.h"
    
    using namespace std;
    
    int main(int argc, char *argv[]){
      
      W3Client w3;
     
      if(w3.Connect("http://google.com/")){
       if(w3.Request("/")){
        char buf[1024]="\0";
        while(w3.Response(reinterpret_cast<unsigned char *>(buf), 1024))
         cout << buf ;
      }
       w3.Close();
      }
      return 0;
    }
  2. Synchronized HTTP POST multiparts/form-data

    int main(int argc, char *argv[]){
     
     W3Client client;
    
     if(client.Connect("http://gooshin.zzem.net/")){
      client.AddPostArgument("f[]", "d:\\log1.txt", true);
      client.AddPostArgument("f[]", "d:\\log2.txt", true);
      client.AddPostArgument("f[]", "d:\\log3.txt", true);
      if(client.Request("/test.php", W3Client::reqPostMultipartsFormdata)){
       char buf[1024]="\0";
       while(client.Response(reinterpret_cast<unsigned char*>(buf), 1024)>0){
        cout << buf << endl;
        memset(buf, 0x00, 1024);
       }
      }
      client.Close();
     }
    
     return 0;
    }
  3. Asynchronized HTTP client

    #include <iostream>
    #include <net/w3c.h>
    #include <wt.h>
    #include <windows.h>
    
    using namespace std;
    
    CRITICAL_SECTION __cs;
    
    class AsDown : public AsyncW3Client, public IWORKERTHREAD {
    public:
     AsDown(unsigned int idx):AsyncW3Client(), IWORKERTHREAD(idx){}
     virtual ~AsDown(){}
    private:
     virtual void OnWork(){
      while(true){
       WaitCompleteRequest();
       unsigned char buf[1024]="\0";
       while(Response(buf, 1024)){
         ::EnterCriticalSection(&__cs);
         cout << reinterpret_cast<char*>(buf);
         ::LeaveCriticalSection(&__cs);
         memset(buf, 0x00, 1024);
       }
       ::Sleep(500);
      }
     }
    };
    void CALLBACK __getstatus(  HINTERNET hInternet,
                   DWORD_PTR dwContext,
                   DWORD dwInternetStatus,
                   LPVOID lpvStatusInformation,
                   DWORD dwStatusInformationLength
                   ){
     AsyncW3Client *pcontext=reinterpret_cast<AsyncW3Client*>(dwContext);
     
     unsigned long nbytes=0;
      ::EnterCriticalSection(&__cs);
      switch(dwInternetStatus){
     case INTERNET_STATUS_SENDING_REQUEST:
      cout << "request sending..." << endl;
      break;
     case INTERNET_STATUS_REQUEST_SENT:
      {
       unsigned long *pnsent=(unsigned long*)lpvStatusInformation;
       cout << "bytes sent: " << *pnsent << endl;
       nbytes+=*pnsent;
       cout << "request sent..." << endl;
      }
      break;
     case INTERNET_STATUS_REQUEST_COMPLETE:
      {
       INTERNET_ASYNC_RESULT *pAsyncRes = 
              (INTERNET_ASYNC_RESULT *)lpvStatusInformation;
       cout << "Function call finished" << endl;
       cout << "dwResult: " << pAsyncRes->dwResult << endl;
       cout << "dwError:  " << pAsyncRes->dwError << endl;
       cout.flush();
       pcontext->SetCompleteRequest();
        cout << "request complete..." << endl;  
      }
      break;
      }
      ::LeaveCriticalSection(&__cs);
     
      return;
    }
    int main(int argc, char *argv[]){ 
     ::InitializeCriticalSection(&__cs);
     AsDown client(3);
     if(client.Connect("http://gooshin.zzem.net/", __getstatus)){
      __wtstart(client);
      client.Request("/test.php");
      Sleep(5000);
      client.InitializePostArguments();
      client.AddPostArgument("f[]", "d:\\log1.txt", true);
      client.AddPostArgument("f[]", "d:\\log2.txt", true);
      client.AddPostArgument("f[]", "d:\\log3.txt", true);
      client.Request("/test.php", AsDown::reqPostMultipartsFormdata);
      Sleep(5000);
      client.InitializePostArguments();
      client.AddPostArgument("f", "sss");
      client.Request("/test2.php", AsDown::reqPost);  
      Sleep(5000);
      
      __wtwait(client);
      client.Close();
     }
     ::DeleteCriticalSection(&__cs);
     return 0;
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Heo Yongseon
Software Developer
Korea (Republic Of) Korea (Republic Of)
Poke tongue | ;-P

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralNot able to run the sample!!membergu@z12-Nov-08 15:41 
QuestionAbout licensememberPrasVM16-Oct-08 0:07 
AnswerRe: About licensememberYongseon Heo16-Oct-08 1:25 
GeneralSmall bug with cookiesmemberoren.shnitzer24-Aug-08 0:17 
GeneralA question about AsyncW3ClientmemberProtocol_yatsu23-Feb-08 6:49 
QuestionHow to manage a Timeout?membercact26-Sep-07 0:39 
GeneralYour Post Method Fails!!!memberBill SerGio, The Infomercial King29-Jan-07 11:31 
GeneralRe: Your Post Method Fails!!!memberSteve Thresher30-Apr-12 4:55 
Questionquestion about std:string?membertypg30-Aug-06 17:08 
GeneralPOST via SSL does not work for mememberkoehler12-Jul-06 12:32 
Generalif(_hOpen || _hOpen!=INVALID_HANDLE_VALUE)membercp66331110-Jul-06 23:40 
GeneralBug with ::HttpOpenRequest in your class [modified]membersbytov28-Jun-06 23:50 
GeneralRe: Bug with ::HttpOpenRequest in your classmemberGoatboy16028-Aug-06 10:11 
GeneralRe: Bug with ::HttpOpenRequest in your classmemberpraveen7920-Nov-08 23:35 
Generalhere,how to login out yahoo emailmembershellhy26-Jun-06 0:23 
QuestionIWORKERTHREAD [modified]memberdaman37120-Jun-06 7:37 
AnswerRe: IWORKERTHREADmemberdaman37122-Jun-06 8:31 
General222membershellhy13-Jun-06 1:07 
QuestionDialog and String Table all in KOREAN, How do I convert to English ?membercfilorux3-May-06 12:46 
GeneralSessionsmembereusto19-Apr-06 2:15 
GeneralRe: SessionsmemberYongseon Heo19-Apr-06 15:31 
GeneralDownload filemembermeouvn9-Mar-06 16:04 
GeneralRe: Download filemember_aleksei31-Dec-06 3:13 
QuestionPost xml datamembertino5516-Feb-06 22:50 
QuestionSmall bug? or my mistake?memberYails5-Dec-05 5:05 
AnswerRe: Small bug? or my mistake?memberYongseon Heo19-Dec-05 17:09 
Generalurl encodingmembergkutiel22-Oct-05 7:43 
GeneralRe: url encodingmemberYongseon Heo19-Dec-05 17:08 
GeneralProgress in uploading filememberAkbaraka10-Aug-05 4:46 
GeneralRe: Progress in uploading filememberYongseon Heo10-Aug-05 16:09 
GeneralRe: Progress in uploading filemembermarlongrech30-Oct-06 5:53 
GeneralRe: Progress in uploading filemembermarlongrech31-Oct-06 0:06 
QuestionRe: Progress in uploading filememberAngel Kafazov7-Jan-09 4:42 
GeneralCrash / Fix when the connection internet is offline and bug in the return of the function Connect(...).memberalanlive30-Jun-05 21:38 
GeneralBug in AsyncW3ClientmemberDean Hallman24-Jun-05 14:30 
GeneralHTTPS Not Workingsussneverneverland15-Jun-05 6:26 
GeneralRe: HTTPS Not WorkingmemberTomazZ28-Jul-05 3:49 
GeneralRe: HTTPS Not WorkingmemberTomazZ28-Jul-05 3:54 
GeneralRe: HTTPS Not Workingmemberdungbkhn22-Aug-05 18:16 
GeneralRe: HTTPS Not WorkingmemberTomazZ5-Dec-05 2:08 
GeneralRe: HTTPS Not Workingmemberszuzso14-Dec-05 2:40 
GeneralRe: HTTPS Not Workingmembermeouvn8-Mar-06 20:13 
GeneralRe: HTTPS Not Workingmembermeouvn9-Mar-06 16:08 
GeneralRe: HTTPS Not Workingmemberzhirenze9-Dec-06 3:47 
GeneralUnicode VersionmemberSnowshoeMJ20-May-05 9:42 
GeneralRe: Unicode VersionmemberYongseon Heo24-May-05 14:09 
GeneralRe: Unicode Version [modified]memberHongJin Kim13-Jun-06 16:52 
GeneralCan't complie on VS.NET 2003membermoshem10-May-05 6:55 
I get lots of warnings and errors such as:
 
error C2248: 'W3Client::HTTP_COOKIE' : cannot access private typedef declared in class 'W3Client'
d:\src\w3ctest\w3c.h(313) : see declaration of 'W3Client::HTTP_COOKIE'
 
can anyone help ?
GeneralRe: Can't complie on VS.NET 2003memberYongseon Heo10-May-05 14:28 
GeneralCGImemberGur Eliash9-May-05 0:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 4 May 2004
Article Copyright 2004 by Heo Yongseon
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid