Tarea: implementación de la analítica diaria en MQL5 con visualización en línea - página 7

 
¿Alguien tiene algún ejemplo de cómo utilizar esta función, el manual no dice nada al respecto?
 
IvanIvanov:
¿Alguien tiene algún ejemplo de cómo utilizar esta función, porque el manual no dice nada al respecto?

Cómo es el silencio, todo está explicado allí.

Hay ejemplos de WinInet en el código de bezet, y también hay ejemplos probados y que funcionan.

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:

cómo es el silencio, todo está escrito.

Bueno, no todo. Renat dijo

Puedes hacer cualquier cosa con él...

¿Hay algún ejemplo de solicitud POST escrito en la ayuda? ¿O descarga de archivos?

 
fyords:

Bueno, no todos. Renat dijo

¿Hay algún ejemplo de solicitud POST escrito en la Ayuda? ¿O descarga de archivos?

Dice GET, por lo que significa GET-request, si POST, entonces POST-request (con POST-request se pueden enviar más parámetros de petición).

En la variable resultado se escribe lo que hay en el enlace:

https://www.google.com/finance

A continuación, el resultado se escribe en un archivo y el archivo se abre para la escritura como un archivo binario.

ZS: busca en la base de código ejemplos de WinInet, es lo mismo aquí.

 
sanyooooook:

Si dice GET, entonces GET-request, si POST, entonces POST-request (con POST-request también se pueden enviar parámetros de solicitud).

en la variable resultado se escribe lo que es vía enlace:

Además el resultado se escribe en el archivo, el archivo se abre para escribir como binario.

Bueno esto lo entiendo, la ayuda no es un ejemplo.
A continuación, me interesa cargar datos no textuales mediante una petición POST.

Solicitudes de Traceroute, siempre pasadas en la cabecera

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

Aunque para descargar la imagen parece que se necesita

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

Yo lo hacía así, pero no está bien y no está hecho para que encaje en la foto:

//+------------------------------------------------------------------+
//|                                                     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, puedes hacer cualquier cosa con una DLL.
Gracias por el ejemplo.

Estoy interesado en las herramientas habituales, WebRequest.

 
fyords:

No, puedes hacer cualquier cosa con una DLL.

Estoy interesado en las herramientas habituales, WebRequest.

Por analogía con el uso de WinInet, entiendo que sólo tiene un problema con la corrección de la cabecera.
 
sanyooooook:
hacer lo mismo que con WinInet, entiendo que sólo tiene un problema con la cabecera es correcta.
No, el problema es que WebRequest no permite (quizás no sé cómo) generar sus propias cabeceras.
 
¿Dónde quieres publicar?
Razón de la queja: