Compito: implementazione di analisi giornaliere in MQL5 con visualizzazione online - pagina 7

 
Qualcuno ha qualche esempio di come usare questa funzione, il manuale è silenzioso sull'argomento!
 
IvanIvanov:
Qualcuno ha qualche esempio di come usare questa funzione, perché il manuale è silenzioso su questo argomento!

Come è silenzioso, è tutto spiegato lì.

Ci sono esempi di WinInet nel codice di bezet, e ci sono anche esempi funzionanti e testati.

void OnStart()
  {
   string cookie=NULL,headers;
   char post[],result[];
   int res;
//--- для работы с сервером необходимо добавить URL "https://www.google.com/finance" 
//--- в список разрешенных URL (Главное меню->Сервис->Настройки, вкладка "Советники"):
   string google_url="https://www.google.com/finance";
//--- обнуляем код последней ошибки
   ResetLastError();
//--- загрузка html-страницы с Google Finance
   res=WebRequest("GET",google_url,cookie,NULL,50,post,0,result,headers);
//--- проверка ошибок
   if(res==-1)
     {
      Print("Ошибка в WebRequest. Код ошибки  =",GetLastError());
      //--- возможно URL отсутствует в списке, выводим сообщение о необходимости его добавления
      MessageBox("Необходимо добавить адрес '"+google_url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION);
     }
   else
     {
      //--- успешная загрузка
      PrintFormat("Файл успешно загружен, Размер файла =%d байт.",ArraySize(result));
      //--- сохраняем данные в файл
      int filehandle=FileOpen("GoogleFinance.htm",FILE_WRITE|FILE_BIN);
      //--- проверка ошибки
      if(filehandle!=INVALID_HANDLE)
        {
         //--- сохраняем содержимое массива result[] в файл
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- закрываем файл
         FileClose(filehandle);
        }
      else Print("Ошибка в FileOpen. Код ошибки =",GetLastError());
     }
  }
 


 
sanyooooook:

come è silenzioso, è tutto scritto.

Beh, non tutto. Renat ha detto

Ci si può fare di tutto ...

C'è un esempio di richiesta POST scritto nella guida? O il download di file?

 
fyords:

Beh, non tutti. Renat ha detto

C'è un esempio di richiesta POST nell'aiuto? O il download di file?

Dice GET, quindi significa GET-request, se POST, allora POST-request (con POST-request si possono inviare più parametri di richiesta).

Nella variabile risultato è scritto ciò che si trova sul link:

https://www.google.com/finance

Poi il risultato viene scritto in un file e il file viene aperto per la scrittura come file binario.

ZS: cerca nel codice base degli esempi di WinInet, è lo stesso qui.

 
sanyooooook:

Se dice GET, allora GET-request, se POST, allora POST-request (con POST-request possono essere inviati anche i parametri di richiesta).

nella variabile risultato è scritto ciò che è via link:

dopo che il risultato è stato scritto nel file, il file viene aperto per la scrittura come binario.

Beh, questo lo capisco, l'aiuto non è un esempio.
Poi, sono interessato a caricare dati non testuali tramite POST-request.

Richieste Traceroute, sempre passate nell'intestazione

Content-Type: application/x-www-form-urlencoded

Anche se per scaricare l'immagine sembra necessario

Content-Type: multipart/form-data;
Content-Type: image/jpeg
 

Lo facevo così, ma non è giusto e non è fatto per adattarsi all'immagine:

//+------------------------------------------------------------------+
//|                                                     HttpPOST.mq4 |
//|                      Copyright © 2012, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2012, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
#define  INTERNET_FLAG_PRAGMA_NOCACHE                                            0x00000100  // не кешировать страницу
#define  INTERNET_FLAG_KEEP_CONNECTION                                           0x00400000  // не разрывать соединение
#define  INTERNET_FLAG_SECURE                                            0x00800000 
#define  INTERNET_FLAG_RELOAD                                                                            0x80000000  // получать страницу с сервера при обращении к ней
#define  INTERNET_OPEN_TYPE_PRECONFIG  0   // use registry configuration
#define  INTERNET_FLAG_KEEP_CONNECTION   0x00400000  // use keep-alive semantics
#define  INTERNET_SERVICE_HTTP   3

#import "wininet.dll"
        int InternetAttemptConnect(int x);
  int InternetOpenA(string sAgent, int lAccessType, string sProxyName="", string sProxyBypass="", int lFlags = 0);
        int InternetConnectA(int hInternet, string lpszServerName, /*WORD*/ int nServerPort, string lpszUsername, string lpszPassword, int dwService, int dwFlags,  int dwContext);
  int HttpOpenRequestA(int hConnect, string lpszVerb, string lpszObjectName, string lpszVersion, string lpszReferer, string lplpszAcceptTypes, int dwFlags, int dwContext);
  int HttpSendRequestA(int hRequest, string lpszHeaders, int dwHeadersLength, int& lpOptional[], int dwOptionalLength);
  int InternetCloseHandle(int hInet);
//  int InternetReadFile(int hFile, int& sBuffer[], int lNumBytesToRead, int& lNumberOfBytesRead[]);
int InternetReadFile(int hFile, string sBuffer, int lNumBytesToRead, int& lNumberOfBytesRead[]);
#import
        
        string Host="secure.indx.ru";
        string Path="/api/v1/tradejson.asmx";
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
        int h=FileOpen("text.txt", FILE_BIN|FILE_READ); if (h<0) return;
        FileSeek(h, 0, SEEK_SET);       int size=MathFloor(FileSize(h)/4);if(FileSize(h)%4!=0)size++;
        int data[], i=0;        ArrayResize(data, size); // изменили размер
        while (!FileIsEnding(h)) { data[i]=FileReadInteger(h, LONG_VALUE); i++; }
        FileClose(h); // 
        // выводим прочитанный массив для проверки
        string st="";
        for (i=0; i<size; i++) 
        {
                st=st+CharToStr(data[i]&255); st=st+CharToStr(data[i]>>8&255); 
                st=st+CharToStr(data[i]>>16&255); st=st+CharToStr(data[i]>>24&255); 
        }
        Print("Размер файла: "+size*4+"  байт");
        Print("Данные: "+st);
        int hInternetSession, hConnectHandle, hResourceHandle, result;
        if(InternetAttemptConnect(0)!=0) { Print("error InternetAttemptConnect"); return(0); }
        hInternetSession=InternetOpenA("Microsoft Internet Explorer",  INTERNET_OPEN_TYPE_PRECONFIG, "", "", 0); 
        if (hInternetSession<=0) { Print("error InternetOpenA()"); return(0); }
        
        hConnectHandle=InternetConnectA(hInternetSession, Host, 80, "", "", INTERNET_SERVICE_HTTP, 0, 0); 
        if (hConnectHandle<=0) { Print("error InternetConnect()"); return(0); }
        
        hResourceHandle=HttpOpenRequestA(hConnectHandle, 
                                         "POST", 
                                         Path, 
                                         "", 
                                         "", 
                                         "Accept: text/json\r\n", 
                                         INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_RELOAD|INTERNET_FLAG_PRAGMA_NOCACHE, 
                                         0); 
        if (hResourceHandle<=0) { Print("error HttpOpenRequest()"); return(0); }
        Print(hResourceHandle);
        string Head="Content-Type: application/x-www-form-urlencoded";
   int Len=StringLen(Head);
        result=HttpSendRequestA(hResourceHandle, Head, Len, data, size);
        Print(result);
        if (result<=0) { Print("error HttpSendRequestA()"); return(0); }
        //Print("Сука вот я дебил!!! )))");
  int     lReturn[]  = {1};
  string  sBuffer    = "";
  string strWebPage="";
  int I=0;
  while (!IsStopped()) {
    if (InternetReadFile(hResourceHandle, sBuffer, 128, lReturn) <= 0 || lReturn[0] == 0) {
    //Print(sBuffer);
      break;
    }
    I++;
    Print(I);
    strWebPage = StringConcatenate(strWebPage, StringSubstr(sBuffer, 0, lReturn[0]));
  }
    Print(strWebPage);
   InternetCloseHandle(hResourceHandle);
        InternetCloseHandle(hConnectHandle);
        InternetCloseHandle(hInternetSession);     
   return(0);
  }
//+------------------------------------------------------------------+
 

No, si può fare qualsiasi cosa con una DLL.
Grazie per l'esempio.

Sono interessato agli strumenti regolari, WebRequest.

 
fyords:

No, si può fare qualsiasi cosa con una DLL.

Sono interessato agli strumenti regolari, WebRequest.

Per analogia con l'uso di WinInet, capisco che hai solo un problema con l'intestazione corretta.
 
sanyooooook:
fare lo stesso con WinInet, capisco che hai solo un problema con l'intestazione corretta.
No, il problema è che WebRequest non permette (forse non so come) di generare le proprie intestazioni.
 
Dove vuoi postare?
Motivazione: