KeisukeIwabuchi / MQL4-Web

A module for handling WebRequest function comfortably with MQL4.
MIT License
25 stars 18 forks source link

How to add Authorization to the GET and POST Method in MQL4 #1

Closed nad29cob closed 6 months ago

nad29cob commented 3 years ago

Hello,

I had used your Web.mqh which works fine for method Get without adding any parameters..

I would like to know how to add Bearer Token for Authorization to the Method GET in MQL4.

Below Visual Studio C# Code works fine

image

The highlighted one is the Bearer Token which I need to provide to get the successful response. Kindly let me know how to add this bearer token in the MQL4 code. Thanks & Regards, Naren

KeisukeIwabuchi commented 3 years ago

Hello,

There is no function to set the Authorization header in Web.mqh. You need to improve the code yourself.

You probably need to make the following changes.

It is line 85 of Web.mqh that needs to be changed. The fourth argument of the WebRequest function is the request header setting.

static bool Web::request(const string  url,
                         const string  method,
                               char   &data[],
                               string &response)
{
   if(IsTesting()) return(false);

   int    status_code;
   string headers;
   char   result[];
   uint   timeout = GetTickCount();

   status_code = WebRequest(method, 
                            url, 
                            NULL, 
                            NULL,  // -> "Autuorization: Bearer XXXXXXXX"
                            HTTP_TIMEOUT, 
                            data, 
                            ArraySize(data), 
                            result, 
                            headers);

   if(status_code == -1) {
      if(GetTickCount() > timeout + HTTP_TIMEOUT) {
         Print("WebRequest get timeout");
      }
      else {
         Print(ErrorDescription(GetLastError()));
      }
      return(false);
   }

   response = CharArrayToString(result, 0, ArraySize(result), CP_UTF8);
   Web::resetPrameter();

   return(true);
}

Thanks & Regards,

nad29cob commented 3 years ago

Thank you very much for your time and suggestion :-)

nad29cob commented 3 years ago

I had modified the code in Line 85 as below

image

But unfortunately I do not receive a successful response.

I believe the solution provided by you is valid but I am not sure that I am executing in a right way!!

Thanks & Regards Naren

mqlmaster commented 9 months ago

Hi, Thanks for the code. Could you give example how to send image using web.mqh?

KeisukeIwabuchi commented 9 months ago

Hi,

Web.mqh is not designed to send images. You should create another function to handle sending images.

I will describe an example of the code I use to send images to LINE Notify.

#define END_POINT_URL "https://notify-api.line.me/api/notify"

input string Token = "";

void SendImage(const string message, const string imagePath)
{
    char imageData[];

    int filehandle = FileOpen(imagePath, FILE_READ | FILE_BIN);
    if (filehandle != INVALID_HANDLE) {
        FileReadArray(filehandle, imageData);
        FileClose(filehandle);
    } else {
        PrintFormat("Error %d", GetLastError());
        return;
    }

    string RequestMethod = "POST";

    string boundary = "boundary-data-123456789";

    string imageHeader;
    imageHeader += StringFormat("--%s\r\n", boundary);
    imageHeader += StringFormat("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n", "imageFile", imagePath);
    imageHeader += StringFormat("Content-Type: image/jpeg\r\n\r\n", "");

    string messageHeader;
    messageHeader += StringFormat("--%s\r\n", boundary);
    messageHeader += StringFormat("Content-Disposition: form-data; name=\"%s\"\r\n", "message");
    messageHeader += StringFormat("Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n", "");

    string messageText = StringFormat("%s\r\n", message);

    string footer = StringFormat("\r\n--%s--\r\n", boundary);

    char messageData[];
    StringToCharArray(messageText, messageData, 0, WHOLE_ARRAY, CP_UTF8);
    ArrayResize(messageData, ArraySize(messageData) - 1);

    char messageHeaderData[];
    StringToCharArray(messageHeader, messageHeaderData, 0, StringLen(messageHeader), CP_UTF8);

    char imageHeaderData[];
    StringToCharArray(imageHeader, imageHeaderData, 0, StringLen(imageHeader), CP_UTF8);

    char footerData[];
    StringToCharArray(footer, footerData, 0, StringLen(footer), CP_UTF8);

    int length = ArraySize(messageHeaderData) + ArraySize(messageData) + ArraySize(imageHeaderData) + ArraySize(imageData) + ArraySize(footerData);

    string headers;
    headers += StringFormat("Content-Type: multipart/form-data; boundary=%s\r\n", boundary);
    headers += StringFormat("Content-Length: %d\r\n", length);
    headers += StringFormat("Authorization: Bearer %s\r\n\r\n", Token);

    char sendData[];
    ArrayCopy(sendData, messageHeaderData, ArraySize(sendData));
    ArrayCopy(sendData, messageData, ArraySize(sendData));
    ArrayCopy(sendData, imageHeaderData, ArraySize(sendData));
    ArrayCopy(sendData, imageData, ArraySize(sendData));
    ArrayCopy(sendData, footerData, ArraySize(sendData));

    char result[];
    string result_headers = NULL;
    int timeout = 10000;
    int res = WebRequest(RequestMethod, END_POINT_URL, headers, timeout, sendData, result, result_headers);

    if (res == -1) {
        Print("Error in WebRequest. Error code = ", GetLastError());
    } else {
        string result_text = StringConcatenate(CharArrayToString(result, 0, ArraySize(result)));
        int replaced = StringReplace(result_text, "\"", "");
        Print("result_text : " + result_text);
    }
}

The argument imagePath is the name of the image file in the Files folder of the data folder.

Thanks & Regards,

mqlmaster commented 9 months ago

Thanks a lot for the code, I really appreciate it.

nad29cob commented 6 months ago

Hello,

There is no function to set the Authorization header in Web.mqh. You need to improve the code yourself.

You probably need to make the following changes.

It is line 85 of Web.mqh that needs to be changed. The fourth argument of the WebRequest function is the request header setting.

static bool Web::request(const string  url,
                         const string  method,
                               char   &data[],
                               string &response)
{
   if(IsTesting()) return(false);

   int    status_code;
   string headers;
   char   result[];
   uint   timeout = GetTickCount();

   status_code = WebRequest(method, 
                            url, 
                            NULL, 
                            NULL,  // -> "Autuorization: Bearer XXXXXXXX"
                            HTTP_TIMEOUT, 
                            data, 
                            ArraySize(data), 
                            result, 
                            headers);

   if(status_code == -1) {
      if(GetTickCount() > timeout + HTTP_TIMEOUT) {
         Print("WebRequest get timeout");
      }
      else {
         Print(ErrorDescription(GetLastError()));
      }
      return(false);
   }

   response = CharArrayToString(result, 0, ArraySize(result), CP_UTF8);
   Web::resetPrameter();

   return(true);
}

Thanks & Regards,

I am not able to get the response using the above solution. Could you please help me to resolve the issue

nad29cob commented 6 months ago

GET Method This is what I am trying to achieve using mql4 code

KeisukeIwabuchi commented 6 months ago

I changed line 85 and then tried mine. The response came back, but there seemed to be a security error. I am not authorized to use the API you are trying to use, so I cannot help you to the end.

nad29cob commented 6 months ago

I tried using the Github API : https://api.github.com/user along with Bearer Token by modifying the line 85 of the code like

status_code = WebRequest(method, url, NULL, "Authorization: Bearer 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",//NULL, HTTP_TIMEOUT, data, ArraySize(data), result, headers);

It still doesn't add the Bearer Token properly and I get a response like image

Below is the inputs from POSTMAN which works fine image

Could you please tell me what am I doing wrong in my approach? Thank you in Advance

nad29cob commented 6 months ago

I solved the issue with the help of a friend the correct way to add the Authorization in line 85 is image

nad29cob commented 6 months ago

Please address the issue with some more attention as I spent almost a weeks time on this solve this one line of code. When someone has an issue please help by giving them more options on how to solve that . Thank you