Tarefa: implementação de análises diárias em MQL5 com exibição online - página 7

 
Se alguém tem exemplos de como utilizar esta função, o manual é omisso sobre o assunto!
 
IvanIvanov:
Alguém tem exemplos de como utilizar esta função porque o manual é omisso sobre este tópico!

Como é que é silencioso, está tudo aí explicado.

Há exemplos de WinInet no código da luneta, e há também exemplos funcionais e testados.

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:

como é silencioso, está tudo anotado.

Bem, nem tudo. Renat disse

Pode fazer qualquer coisa com ele ...

Existe um exemplo de pedido de PÓS-ENVOLVIMENTO escrito em ajuda? Ou descarregamento de ficheiros?

 
fyords:

Bem, nem todos eles. Renat disse

Existe um exemplo de pedido de ajuda no POST? Ou descarregamento de ficheiros?

Diz GET, portanto significa GET-request, se POST, então POST-request (com POST-request mais parâmetros de pedido podem ser enviados).

No resultado variável está escrito o que está na ligação:

https://www.google.com/finance

Depois o resultado é escrito num ficheiro e o ficheiro é aberto para escrita como um ficheiro binário.

ZS: procurar exemplos WinInet na base de códigos, aqui é o mesmo.

 
sanyooooook:

Se diz GET, então GET-request, se POST, então POST-request (com POST-request também podem ser enviados parâmetros de pedido).

no resultado variável é escrito o que é via link:

além disso o resultado é escrito no ficheiro, o ficheiro é aberto para escrita como binário.

Bem, isto eu compreendo, a ajuda não é um exemplo.
A seguir, estou interessado em carregar dados não textuais por pedido POST.

Pedidos de traceroute, sempre passados no cabeçalho

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

Embora para descarregar a imagem pareça ser necessário

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

Costumava fazê-lo assim, mas não está certo e não foi feito para se ajustar ao quadro:

//+------------------------------------------------------------------+
//|                                                     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);
  }
//+------------------------------------------------------------------+
 

Não, pode fazer qualquer coisa com uma DLL.
Obrigado pelo exemplo.

Estou interessado nas ferramentas regulares, WebRequest.

 
fyords:

Não, pode fazer qualquer coisa com uma DLL.

Estou interessado nas ferramentas regulares, WebRequest.

Faça por analogia com a utilização do WinInet, compreendo que apenas tem um problema com o cabeçalho correcto.
 
sanyooooook:
fazer o mesmo que com o WinInet, compreendo que está apenas a ter um problema com o cabeçalho correcto.
Não, o problema é que o WebRequest não permite (talvez eu não saiba como) gerar os seus próprios cabeçalhos.
 
Onde quer afixar?