Click here to Skip to main content
15,868,141 members
Articles / Desktop Programming / MFC
Article

WWW (HTTP/HTTPS/FTP) Client using WININET

Rate me:
Please Sign up or sign in to vote.
4.04/5 (29 votes)
3 May 2004CPOL 314K   10.8K   95   87
Synchronized/asynchronized WWW client: HTTP/HTTPS GET, POST, POST multiparts/form-data supported. FTP GET FILE, PUT FILE supported too.

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)


Written By
Software Developer
Korea (Republic of) Korea (Republic of)
Poke tongue | ;-P

Comments and Discussions

 
GeneralRe: https sample Pin
StanSpielbusch21-Jan-05 10:43
StanSpielbusch21-Jan-05 10:43 
Generaltwo small requests Pin
User 138647515-Dec-04 7:44
User 138647515-Dec-04 7:44 
GeneralRe: two small requests Pin
Heo Yongseon23-Dec-04 15:58
Heo Yongseon23-Dec-04 15:58 
GeneralHelp!Thank you Pin
alai25811-Dec-04 15:22
alai25811-Dec-04 15:22 
GeneralRe: Help!Thank you Pin
Heo Yongseon23-Dec-04 15:27
Heo Yongseon23-Dec-04 15:27 
GeneralUpload File Using Synchronised Post Pin
Griv28-Sep-04 16:51
Griv28-Sep-04 16:51 
Generalhttps for Request and Get Pin
mesamis14-Sep-04 2:44
mesamis14-Sep-04 2:44 
GeneralRe: https for Request and Get Pin
Heo Yongseon14-Sep-04 14:47
Heo Yongseon14-Sep-04 14:47 
GeneralRe: https for Request and Get Pin
georgezhangca15-Nov-04 8:10
georgezhangca15-Nov-04 8:10 
Generalfatal error LNK1104 Pin
ozgul4-Sep-04 4:53
ozgul4-Sep-04 4:53 
GeneralRe: fatal error LNK1104 Pin
Heo Yongseon5-Sep-04 14:35
Heo Yongseon5-Sep-04 14:35 
Questionhow to deal with 404 error? Pin
quace19-Jul-04 0:22
quace19-Jul-04 0:22 
AnswerRe: how to deal with 404 error? Pin
Heo Yongseon19-Jul-04 14:03
Heo Yongseon19-Jul-04 14:03 
Questiondeal with cgi downloader script? Pin
sl33pycat13-May-04 3:51
sl33pycat13-May-04 3:51 
AnswerRe: deal with cgi downloader script? Pin
Heo Yongseon13-May-04 7:46
Heo Yongseon13-May-04 7:46 
GeneralRe: deal with cgi downloader script? Pin
sl33pycat13-May-04 16:15
sl33pycat13-May-04 16:15 
Questionprogress? Pin
cihef72126-May-04 21:06
cihef72126-May-04 21:06 
AnswerRe: progress? Pin
Heo Yongseon6-May-04 21:23
Heo Yongseon6-May-04 21:23 
GeneralASYNC POST Pin
tyounsi4-May-04 14:42
tyounsi4-May-04 14:42 
GeneralRe: ASYNC POST Pin
Heo Yongseon6-May-04 15:27
Heo Yongseon6-May-04 15:27 
GeneralRe: ASYNC POST Pin
tyounsi8-May-04 6:52
tyounsi8-May-04 6:52 
GeneralRe: ASYNC POST Pin
tyounsi9-May-04 0:47
tyounsi9-May-04 0:47 
GeneralSample Project Needed Pin
tsz4-May-04 8:59
tsz4-May-04 8:59 
GeneralRe: Sample Project Needed Pin
Heo Yongseon5-May-04 4:25
Heo Yongseon5-May-04 4:25 
GeneralRe: Sample Project Needed Pin
tsz5-May-04 5:24
tsz5-May-04 5:24 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.