Fermer2
robinHoodLe 03/03/2009 à 18:02
hello :- )

bon, je commence à pas mal utiliser curl, et je viens de me faire un petit bout de code pour simplifier son utilisation
en espérant que ça puisse aider qq..

deux fichiers :
mycurl.h#include "../StdAfx.h" #include <stdio.h> #include <stdlib.h> #include "../curl/curl.h" #include "../curl/types.h" #include "../curl/easy.h" //#include "../console.h" #include "../log.h" struct MemoryStruct { char *memory; size_t size; }; size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data); class cURL {      //private:      public:      CURL *handle;      struct MemoryStruct *page;      char lastUrl[2048];      char findStr[1024];       cURL(void);      ~cURL(void);      void init(void);      void  logTo(const char*path);      const char * download(char*path,char*post=0);      char * find(char*start,char*end,char*out=0);      char * pfind(char*buffer,char*start,char*end,char*out); }; int curlShareInit(void); void curlStart(void); void curlEnd(void);

mycurl.cpp#include "StdAfx.h" #include "mycurl.h" int iscookiesblocked = 0; int isdnsblocked = 0; int isdatablocked = 0; CURLSH * curl_share_handle = 0; size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size * nmemb;   struct MemoryStruct *mem = (struct MemoryStruct *)data;   mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);   if (mem->memory) {     memcpy(&(mem->memory[mem->size]), ptr, realsize);     mem->size += realsize;     mem->memory[mem->size] = 0;   }   return realsize; } /* lock callback */ void lock(CURL *handle, curl_lock_data data, curl_lock_access access,           void *useptr ) {   const char *what;   switch ( data ) {     case CURL_LOCK_DATA_SHARE:       what = "share ";        if(isdatablocked) while(isdatablocked) Sleep(1);        isdatablocked=1;       break;     case CURL_LOCK_DATA_DNS:       what = "dns   ";        if(isdnsblocked) while(isdnsblocked) Sleep(1);        isdnsblocked=1;       break;     case CURL_LOCK_DATA_COOKIE:       what = "cookie";        if(iscookiesblocked) while(iscookiesblocked) Sleep(1);        iscookiesblocked=1;       break;     default:       fprintf(stderr, "lock: no such data: %d\n",data);        system("pause");       return;   }   //printf("lock:   %s  <%s>\n", what, (char *)useptr);  } /* unlock callback */ void unlock(CURL *handle, curl_lock_data data, void *useptr ) {   const char *what;   switch ( data ) {     case CURL_LOCK_DATA_SHARE:       what = "share ";        if(!isdatablocked) while(!isdatablocked) Sleep(1);        isdatablocked=0;       break;     case CURL_LOCK_DATA_DNS:       what = "dns   ";        if(!isdnsblocked) while(!isdnsblocked) Sleep(1);           isdnsblocked=0;       break;     case CURL_LOCK_DATA_COOKIE:       what = "cookie";         if(!iscookiesblocked) while(!iscookiesblocked) Sleep(1);           iscookiesblocked=0;       break;     default:       fprintf(stderr, "unlock: no such data: %d\n",data);        system("pause");       return;   }   //printf("unlock: %s  <%s>\n", what, (char *)useptr);  } //log_file winlog("winlog.txt"); char *Utf8ToAnsi(const char * utf8, int len) {     char *utf8str = NULL;      int length = MultiByteToWideChar(CP_UTF8, 0, utf8, len, NULL, NULL );      WCHAR *lpszW = NULL;      lpszW = new WCHAR[length+1];      MultiByteToWideChar(CP_UTF8, 0, utf8, -1, lpszW, length );      int length1 = WideCharToMultiByte(CP_ACP, 0, lpszW, length, NULL, 0, NULL, NULL);      utf8str = ( char * ) calloc ( sizeof(char), length1+1 );      WideCharToMultiByte(CP_ACP, 0, lpszW, length, utf8str, length1, NULL, NULL);      utf8str[length1] = 0;      delete[] lpszW;      return utf8str; } cURL::cURL(void) {     page = (struct MemoryStruct *)malloc(sizeof(struct MemoryStruct));      page->memory = 0; page->size = 0;      *lastUrl = *findStr = 0; } void cURL::init(void) {     handle = curl_easy_init();      curl_easy_setopt(handle, CURLOPT_HEADER, 1);      curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);      curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);      curl_easy_setopt(handle, CURLOPT_SSL_VERIFYHOST, 0);      curl_easy_setopt(handle, CURLOPT_COOKIEJAR, "cookies");      curl_easy_setopt(handle, CURLOPT_COOKIEFILE, "cookies");      curl_easy_setopt(handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");      curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);      if(curl_share_handle)           curl_easy_setopt(handle, CURLOPT_SHARE, curl_share_handle); } void cURL::logTo(const char * path) {     log_file log(path);      log.mem2log(page->memory,page->size); } cURL::~cURL(void) {     curl_easy_cleanup(handle);      if(page) free(page); } const char *cURL::download(char*path,char*post) {     if(!handle || !page) return "error";      if(page->memory) free(page->memory);      page->memory = 0; page->size = 0;      if(post) curl_easy_setopt(handle, CURLOPT_POSTFIELDS,post);      curl_easy_setopt(handle, CURLOPT_POST, (post!=0));      curl_easy_setopt(handle, CURLOPT_REFERER, lastUrl); strcpy(lastUrl,path);      curl_easy_setopt(handle, CURLOPT_WRITEDATA, (void*)page);      curl_easy_setopt(handle, CURLOPT_URL, path);      CURLcode returnValue = curl_easy_perform(handle);            if(page->size)           if(strstr(page->memory,"UTF-8"))           {     char * str = Utf8ToAnsi(page->memory,page->size);                CharToOem(str,str);                free(page->memory);                page->memory = str;                page->size   = strlen(page->memory);           }      if(returnValue) return curl_easy_strerror(returnValue);      return 0; } char * cURL::pfind(char*buffer,char*start, char*end, char*out=0) {     if(!buffer || !start || !end) return 0;      int startSize = strlen(start);      char * startptr = strstr(buffer,start);      if(!startptr) return 0;      char * endptr   = strstr(startptr+startSize,end);      if(!endptr)   return 0;      int valueSize = endptr - (startptr+startSize);      if(valueSize > 1023) return 0;      //static char internalbuffer[10240];      if(!out) out = findStr;      memcpy(out,&startptr[startSize],valueSize);      out[valueSize] = 0;      if(out != findStr) return &endptr[strlen(end)];      return out; } char * cURL::find(char*start, char*end, char*out) {     if(!page->size || !page->memory || !start || !end) return 0;      return pfind(page->memory,start,end,out); } int curlShareInit(void) {     CURLSHcode scode;      curl_share_handle = curl_share_init();      scode = curl_share_setopt(curl_share_handle,CURLSHOPT_SHARE,CURL_LOCK_DATA_COOKIE);      if ( CURLSHE_OK != scode ) return 0;      scode = curl_share_setopt(curl_share_handle,CURLSHOPT_SHARE,CURL_LOCK_DATA_DNS);      if ( CURLSHE_OK != scode ) return 0;      scode = curl_share_setopt(curl_share_handle, CURLSHOPT_LOCKFUNC,   lock);      if ( CURLSHE_OK != scode ) return 0;      scode = curl_share_setopt(curl_share_handle, CURLSHOPT_UNLOCKFUNC, unlock);      if ( CURLSHE_OK != scode ) return 0;      scode = curl_share_setopt(curl_share_handle, CURLSHOPT_USERDATA,   "muhuhuhahahaha!");      if ( CURLSHE_OK != scode ) return 0;      return 1; } void curlStart(void) {     curl_global_init(CURL_GLOBAL_ALL); } void curlEnd(void) {     if(curl_share_handle)           curl_share_cleanup(curl_share_handle);      curl_global_cleanup(); }
       } else Sleep(30000);      };   } }; qq lignes montrant comment initialiser tout ca #include "mycurl/mycurl.h" // on utilisera curl via 3 objets cURL auction; // un pour recuperer le temps restant dans les encheres cURL arene; // un pour le combat dans les arenes cURL player; // pour le log et recup des info des joueurs int main(void) {     curlStart(); // init générale de curl      curlShareInit(); // nous voulons partager les cookies entre objets      // init des objets      player.init();      arene.init();      auction.init();      // et voila, rien d'autre à faire tout est initialisé      // à partir de la tout votre blabla pour dl des truc      logToGame();      auctionTimer auctionThread;      auctionThread.StartAndWait();      while(1)      {     unsigned int SleepTime = arenaFight();           if(!SleepTime)     logToGame();           else  {     int m = SleepTime/60;                     int s = SleepTime - (m*60);                     shell.printc(JAUNE,"\nnow waiting %im %is",m,s);                     for(int n=0;n<m;n++)                     {     shell.printc(JAUNE,".");                          Sleep(60500);                     };                     shell.printc(VERT,".");                     Sleep(s*1000);                     printf("\n");                }      };      auctionThread.Terminate();      // fonction de fermeture de curl      curlEnd();      return 0; } // exemple du thread pour le temps restant dans l'enchere class auctionTimer:public CThread { public:   void OnRunning()   {     char url[1024];      char lastTime[1024];      char *timeStr;      int isveryshort=0;      *url = *lastTime = 0;      //Sleep(5000);     //shell.printc(JAUNE,"\nan hello from auction timer thread !\n");      while(1)      {                sprintf(url,"%sindex.php?mod=auction&sh=%s",server,shkey);           const char * rtn = auction.download(url);           if(rtn)           {     shell.printc(ROUGE,"! error !");                //logToGame();           }           //system("pause");           auction.logTo("auction.html");           timeStr = auction.find("description_span_right\"><b>","</b></span>");           if(timeStr)           {     if(!strcmp("very short",timeStr))                {     if(!isveryshort) isveryshort=30;                     shell.printc(ROUGE,"\n ** time left for auction less than %im!\n\a",isveryshort);                } else     { isveryshort=0;                                                              if(strcmp(lastTime,timeStr))                               {     strcpy(lastTime,timeStr);                                    shell.printc(ROUGE,"\n ** new timestamp for auction : %s\n\a",timeStr);                               }                          }           } else shell.printc(ROUGE,"auction : is logged ?");                      //system("pause");           if(isveryshort)           {     if(isveryshort > 5)                {     Sleep(300000); isveryshort-=5;                }     else { Sleep(60000); isveryshort--; }