Download MetaTrader 5

WebRequest

The function sends an HTTP request to a specified server. The function has two versions:

1. Sending simple requests of type "key=value" using the header Content-Type: application/x-www-form-urlencoded.

int  WebRequest(
   const string      method,           // HTTP method 
   const string      url,              // URL
   const string      cookie,           // cookie
   const string      referer,          // referer
   int               timeout,          // timeout
   const char        &data[],          // the array of the HTTP message body
   int               data_size,        // data[] array size in bytes
   char              &result[],        // an array containing server response data
   string            &result_headers   // headers of server response
   );

2. Sending a request of any type specifying the custom set of headers for a more flexible interaction with various Web services.

int  WebRequest(
   const string      method,           // HTTP method
   const string      url,              // URL
   const string      headers,          // headers 
   int               timeout,          // timeout
   const char        &data[],          // the array of the HTTP message body
   char              &result[],        // an array containing server response data
   string            &result_headers   // headers of server response
   );

Parameters

method

[in]  HTTP method.

url

[in]  URL.

headers

[in]  Request headers of type "key: value", separated by a line break "\r\n".

cookie

[in]  Cookie value.

referer

[in]  Value of the Referer header of the HTTP request.

timeout

[in]  Timeout in milliseconds.

data[]

[in]  Data array of the HTTP message body.

data_size

[in]  Size of the data[] array.

result[]

[out]  An array containing server response data.

result_headers

[out] Server response headers.

Return Value

HTTP server response code or -1 for an error.

Note

To use the WebRequest() function, add the addresses of the required servers in the list of allowed URLs in the "Expert Advisors" tab of the "Options" window. Server port is automatically selected on the basis of the specified protocol - 80 for "http://" and 443 for "https://".

The WebRequest() function is synchronous, which means its breaks the program execution and waits for the response from the requested server. Since the delays in receiving a response can be large, the function is not available for calls from the indicators, because indicators run in a common thread shared by all indicators and charts on one symbol. Indicator performance delay on one of the charts of a symbol may stop updating of all charts of the same symbol.

The function can be called only from Expert Advisors and scripts, as they run in their own execution threads. If you try to call the function from an indicator, GetLastError() will return error 4014 — "Function is not allowed for call".

WebRequest() cannot be executed in the Strategy Tester.

An example of using the first version of the WebRequest () function:

void OnStart()
  {
   string cookie=NULL,headers;
   char post[],result[];
   int res;
//--- to enable access to the server, you should add URL "https://www.google.com/finance"
//--- in the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
   string google_url="https://www.google.com/finance";
//--- Reset the last error code
   ResetLastError();
//--- Loading a html page from Google Finance
   int timeout=5000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection
   res=WebRequest("GET",google_url,cookie,NULL,timeout,post,0,result,headers);
//--- Checking errors
   if(res==-1)
     {
      Print("Error in WebRequest. Error code  =",GetLastError());
      //--- Perhaps the URL is not listed, display a message about the necessity to add the address
      MessageBox("Add the address '"+google_url+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
     }
   else
     {
      //--- Load successfully
      PrintFormat("The file has been successfully loaded, File size =%d bytes.",ArraySize(result));
      //--- Save the data to a file
      int filehandle=FileOpen("GoogleFinance.htm",FILE_WRITE|FILE_BIN);
      //--- Checking errors
      if(filehandle!=INVALID_HANDLE)
        {
         //--- Save the contents of the result[] array to a file
         FileWriteArray(filehandle,result,0,ArraySize(result));
         //--- Close the file
         FileClose(filehandle);
        }
      else Print("Error in FileOpen. Error code=",GetLastError());
     }
  }

 

An example of using the second version of the WebRequest() function:

#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
#property script_show_inputs
#property description "Sample script posting a user message "
#property description "on the wall on mql5.com"
 
input string InpLogin   ="";             //Your MQL5.com account
input string InpPassword="";             //Your account password
input string InpFileName="EURUSDM5.png"//An image in folder MQL5/Files/
input string InpFileType="image/png";    //Correct mime type of the image
//+------------------------------------------------------------------+
//| Posting a message with an image on the wall at mql5.com          |
//+------------------------------------------------------------------+
bool PostToNewsFeed(string login,string password,string text,string filename,string filetype)
  {
   int    res;     // To receive the operation execution result
   char   data[];  // Data array to send POST requests
   char   file[];  // Read the image here
   string str="Login="+login+"&Password="+password;
   string auth,sep="-------Jyecslin9mp8RdKV"// multipart data separator
//--- A file is available, try to read it
   if(filename!=NULL && filename!="")
     {
      res=FileOpen(filename,FILE_READ|FILE_BIN);
      if(res<0)
        {
         Print("Error opening the file \""+filename+"\"");
         return(false);
        }
      //--- Read file data
      if(FileReadArray(res,file)!=FileSize(res))
        {
         FileClose(res);
         Print("Error reading the file \""+filename+"\"");
         return(false);
        }
      //---
      FileClose(res);
     }
//--- Create the body of the POST request for authorization
   ArrayResize(data,StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8)-1);
//--- Resetting error code
   ResetLastError();
//--- Authorization request
   res=WebRequest("POST","https://www.mql5.com/en/auth_login",NULL,0,data,data,str);
//--- If authorization failed
   if(res!=200)
     {
      Print("Authorization error #"+(string)res+", LastError="+(string)GetLastError());
      return(false);
     }
//--- Read the authorization cookie from the server response header
   res=StringFind(str,"Set-Cookie: auth=");
//--- If cookie not found, return an error
   if(res<0)
     {
      Print("Error, authorization data not found in the server response (check login/password)");
      return(false);
     }
//--- Remember the authorization data and form the header for further requests
   auth=StringSubstr(str,res+12);
   auth="Cookie: "+StringSubstr(auth,0,StringFind(auth,";")+1)+"\r\n";
//--- If there is a data file, send it to the server
   if(ArraySize(file)!=0)
     {
      //--- Form the request body
      str="--"+sep+"\r\n";
      str+="Content-Disposition: form-data; name=\"attachedFile_imagesLoader\"; filename=\""+filename+"\"\r\n";
      str+="Content-Type: "+filetype+"\r\n\r\n";
      res =StringToCharArray(str,data);
      res+=ArrayCopy(data,file,res-1,0);
      res+=StringToCharArray("\r\n--"+sep+"--\r\n",data,res-1);
      ArrayResize(data,ArraySize(data)-1);
      //--- Form the request header
      str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
      //--- Reset error code
      ResetLastError();
      //--- Request to send an image file to the server
      res=WebRequest("POST","https://www.mql5.com/upload_file",str,0,data,data,str);
      //--- check the request result
      if(res!=200)
        {
         Print("Error sending a file to the server #"+(string)res+", LastError="+(string)GetLastError());
         return(false);
        }
      //--- Receive a link to the image uploaded to the server
      str=CharArrayToString(data);
      if(StringFind(str,"{\"Url\":\"")==0)
        {
         res     =StringFind(str,"\"",8);
         filename=StringSubstr(str,8,res-8);
         //--- If file uploading fails, an empty link will be returned
         if(filename=="")
           {
            Print("File sending to server failed");
            return(false);
           }
        }
     }
//--- Create the body of a request to post an image on the server
   str ="--"+sep+"\r\n";
   str+="Content-Disposition: form-data; name=\"content\"\r\n\r\n";
   str+=text+"\r\n";
//--- The languages in which the post will be available on mql5.com 
   str+="--"+sep+"\r\n";
   str+="Content-Disposition: form-data; name=\"AllLanguages\"\r\n\r\n";
   str+="on\r\n";
//--- If the picture has been uploaded on the server, pass its link
   if(ArraySize(file)!=0)
     {
      str+="--"+sep+"\r\n";
      str+="Content-Disposition: form-data; name=\"attachedImage_0\"\r\n\r\n";
      str+=filename+"\r\n";
     }
//--- The final string of the multipart request
   str+="--"+sep+"--\r\n";
//--- Out the body of the POST request together in one string
   StringToCharArray(str,data,0,WHOLE_ARRAY,CP_UTF8);
   ArrayResize(data,ArraySize(data)-1);
//--- Prepare the request header  
   str=auth+"Content-Type: multipart/form-data; boundary="+sep+"\r\n";
//--- Request to post a message on the user wall at mql5.com
   res=WebRequest("POST","https://www.mql5.com/ru/users/"+login+"/wall",str,0,data,data,str);
//--- Return true for successful execution
   return(res==200);
  }
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- Post a message on mql5.com, including an image, the path to which is taken from the InpFileName parameter
   PostToNewsFeed(InpLogin,InpPassword,"Checking the expanded version of WebRequest\r\n"
                  "(This message has been posted by the WebRequest.mq5 script)",InpFileName,InpFileType);
  }
//+------------------------------------------------------------------+

 


Updated: 2015.12.25