Task: implementation of daily analytics in MQL5 with online display - page 7

 
Does anyone have any examples of how to use this function, the manual is silent on the subject!
 
IvanIvanov:
Does anyone have any examples of how to use this function because the manual is silent on this topic!

How is it silent, it's all explained there.

There are examples of WinInet in the bezet code, and there are also working, tested examples.

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:

how it's silent, it's all written down.

Well, not all of it. Renat said

You can do anything with it ...

Is there an example of POST request written in help? Or file download?

 
fyords:

Well, not all of them. Renat said

Is there an example of POST request in help? Or file download?

It says GET, so it means GET-request, if POST, then POST-request (with POST-request more request parameters can be sent).

In the variable result is written what is on the link:

https://www.google.com/finance

Then the result is written to a file and the file is opened for writing as a binary file.

ZS: search the code base for WinInet examples, it's the same here.

 
sanyooooook:

If it says GET, then GET-request, if POST, then POST-request (with POST-request also request parameters can be sent).

into the variable result is written what is via link:

further the result is written to the file, the file is opened for writing as binary.

Well this I understand, the help is not an example.
Next, I am interested in loading non-text data by POST-request.

Traceroute requests, always passed in the header

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

Although to download the image seems to need

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

I used to do it like this, but it's not right and it's not made to fit the picture:

//+------------------------------------------------------------------+
//|                                                     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, you can do anything with a DLL.
Thanks for the example.

I'm interested in the regular tools, WebRequest.

 
fyords:

No, you can do anything with a DLL.

I'm interested in the regular tools, WebRequest.

Do by analogy with using WinInet, as I understand it so you just have a problem with the correctness of the header.
 
sanyooooook:
do the same as with WinInet, I understand that you just have a problem with the header being correct.
No, the problem is that WebRequest doesn't allow (maybe I don't know how) to generate its own headers.
 
Where do you want to post?
Reason: