and again dll and market - page 18

 

I think I'm getting somewhere with authorisation.

Реter Konow:

So ask Roman how to do authorisation on the IBM server withWebRequest, that's the key question!

Roman, thanks for the comment! I think we'll manage with authorization as well.

Now about a few parameters. In help on WebRequest it's indicated

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

The variable headers itself is of type string

What do you mean, the string contains a line break character, i.e. the end of the string?

Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • www.mql5.com
Dozens of new automated trading applications appear in the MQL5 Market every day. Choose the right app among 10,000 products and forget about unnecessary routine operations of manual trading. Sell your algorithmic trading programs through the largest store of trading applications! Kiss on billions on EURUSD The provided robot (KOB) is a result...
 
Nikolai Karetnikov:

you must be right, and the screenshot from postman, where the output pair is written in the http request header is explained differently )

i suspect we're still talking about the same thing, but in different words )

I don't know how badly postman is written, what it is, and what it has to do with your problem...

but 90% is solved by reading, and it's up to the person solving the problem to read it.

It's a pretty typical thing - there is documentation of Rest-API service (have you read it by the way??) , you are lucky that they gave an example with curl and no need to parse other languages... and you have to use WebRequest MT.

The curl starts, the protocol is shown on the screen - what headers from parameters are generated and sent, what is received back, how it is understood and where it is put.

And it is directly visible what to send to WebRequest

---

 
Maxim Kuznetsov:

I don't know how badly the postman is written, what it is, or what it has to do with your problem...

but 90% is solved by reading, and it's up to the person who solves the problem to read it.

It's a pretty typical thing - there is documentation of Rest-API service (have you read it by the way??) , you are lucky that they gave an example with curl and no need to parse other languages... and you have to use WebRequest MT.

The curl starts, the protocol is shown on the screen - what headers from parameters are generated and sent, what is received back, how it is understood and where it is put.

And it is directly visible what to send to WebRequest

---

read, read ) Figuring it out and progress is being made.

 
Nikolai Karetnikov:

I think I'm getting there.

Roman, thanks for the comment! I think we'll manage with the authorisation as well.

Now about a few parameters. In help on WebRequest it says

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

The variable headers itself is of type string

What do you mean, the string contains a line break character, i.e. a line break character?

The header may contain more than one key/value string, so a line break is used.
The double hyphenation"\r\n\r\n" must be placed at the end of the header.
This is how the server understands the end of the header, which is an http standard.
After the double hyphenation comes the body of the request or response.

The
WebRequest function separates these blocks for convenience.
For headers its own parameter, for the body its own.
But the syntax of writing the request, requires compliance with the standard http.

 
Carry on, Lieutenant.
 

//+------------------------------------------------------------------+
//|                                                   WebRequest.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   string cookie=NULL,headers;
   char   post[],result[];
   string url="https://example-files.online-convert.com/audio/wav/example.wav";
//--- для работы с сервером необходимо добавить URL "https://finance.yahoo.com"
//--- в список разрешенных URL (Главное меню->Сервис->Настройки, вкладка "Советники"):
//--- обнуляем код последней ошибки
   ResetLastError();
//--- загрузка html-страницы с Yahoo Finance
   int res=WebRequest("GET",url,cookie,NULL,5000,post,0,result,headers);
   if(res==-1)
     {
      Print("Ошибка в WebRequest. Код ошибки  =",GetLastError());
      //--- возможно, URL отсутствует в списке, выводим сообщение о необходимости его добавления
      MessageBox("Необходимо добавить адрес '"+url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION);
     }
   else
     {
      if(res==200)
        {
         //--- успешная загрузка
         PrintFormat("Файл успешно загружен, размер %d байт.",ArraySize(result));
         //PrintFormat("Заголовки сервера: %s",headers);
         //--- сохраняем данные в файл
         int filehandle=FileOpen("example.wav",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- сохраняем содержимое массива result[] в файл
            FileWriteArray(filehandle,result,0,ArraySize(result));
            //--- закрываем файл
            FileClose(filehandle);
            Sleep(1*1000);
            PlaySound("\\Files\\example.wav");
           }
         else
            Print("Ошибка в FileOpen. Код ошибки =",GetLastError());
        }
      else
         PrintFormat("Ошибка загрузки '%s', код %d",url,res);
     }
  }
//+------------------------------------------------------------------+

from this websitehttps://example-files.online-convert.com/audio/wav/example.wav

downloads this "example.wav" file

and after downloading it, it playsPlaySound("\\Files\\\example.wav");

-------------------------------------------------

But the meaning of this function ??? I don't think so!

 

Well, gentlemen, let's move on, shall we?


//+------------------------------------------------------------------+
//|                                                   WebRequest.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   string cookie=NULL,headers;
   char   post[],result[];
   char cost_char_data[];
   string  result_headers;
   
   ResetLastError();
   ArrayFree(result);
  // headers = "Authorization: Basic YXBpa2V5OkdSMWJiM3pWTXM5ZmNOS0w2cEE5LTV6ajlwdFdsaUN1NmVoOW91cFVucFpC/r/n";
   headers = "Authorization: Basic YXBpa2V5OkdSMWJiM3pWTXM5ZmNOS0w2cEE5LTV6ajlwdFdsaUN1NmVoOW91cFVucFpC";
//   headers = headers + "Accept: audio/wav";
   //headers = headers + "Accept: audio/wav/r/n";
  // headers = headers + "Accept: audio/wav/r/n";
 
   string url="https://api.eu-gb.text-to-speech.watson.cloud.ibm.com/instances/9886a3ce-5734-455f-8f78-7a56381da686/v1/synthesize?text=TEST";
               
   int res = WebRequest("GET",url,headers,1000,cost_char_data,result,result_headers);

   if(res==-1)
     {
      printf("Ошибка в WebRequest. Код ошибки  =",GetLastError());
      //--- возможно, URL отсутствует в списке, выводим сообщение о необходимости его добавления
      MessageBox("Необходимо добавить адрес '"+url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION);
     }
   else
     {
      if(res==200)
        {
         //--- успешная загрузка
         printf("Файл успешно загружен, размер %d байт.",ArraySize(result));
         printf("Заголовки сервера: %s",result_headers);
         //--- сохраняем данные в файл
         int filehandle=FileOpen("testmql5.ogg",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- сохраняем содержимое массива result[] в файл
            FileWriteArray(filehandle,result,0,WHOLE_ARRAY);
            //--- закрываем файл
            FileClose(filehandle);
            printf("FileClose");
            
           }
         else
            printf("Ошибка в FileOpen. Код ошибки =",GetLastError());
        }
      else
         printf("Ошибка загрузки '%s', код %d",url,res);
     }
  }
//+------------------------------------------------------------------+


First of all, let's simplify the code of the request itself as much as possible. Let's leave only one header - the authorization itself, which still works! In this case, without any additional headers, IBM server will give us a stream in .ogg audio format. To hell with it, we think, let's make something work first. Let's abandon futile attempts to format stream to wav with additional headers and deal with .ogg (by the way, similar mistake with WebRequest syntaxhttps://www.mql5.com/en/forum/310891#comment_16643324 )

The script gets logged into the server and hangs. Ok, let's run it in debug mode or something...

see, no? )


We drop the script from the graph, but for some reason it doesn't stop executing completely, it just interrupts the synchronous WebRequest and continues, which is generally to our advantage.

Let's move on. In char result[] we now have an .ogg stream and we write it to a file.

File gets 6Kb too (also, because curl or postman query with the same parameters returns 6Kb .ogg file, which plays properly! Good to hear the word Test ))))


Now we write all char array to file. Specially specify that we should not measure array size, but takeWHOLE_ARRAY.

That is how it looks now:

The only problem is, the curl file plays fine, but our file, for some reason, doesn't.

Let's look inside both files



File downloaded by curl at bottom, filled from WebRequest stream into binary at top

See these blobs 00000089, 00000004 in the top file testmql5.ogg? ))) Is it a bonus program or what? ))) Where did it all come from ))))))))


Summarizing

1. The syntax is still a mystery to me. Only managed to authenticate to the server, attempts to add other headers have failed so far

2. i wonder if WebRequest receives stream with sprinkles, or i'm writing it to a file incorrectly, but the format of .ogg file obtained from char array result using WebRequest method is not correct.

Rotten tomatoes welcome!

Send headers via WebRequest()
Send headers via WebRequest()
  • 2019.04.15
  • www.mql5.com
Hi, I am trying to use WebRequest to send a header and get a response. Basically I have the follow parameters: url: "http://www.b3.com.br/main...
 
Alexsandr San:

from this websitehttps://example-files.online-convert.com/audio/wav/example.wav

downloads this "example.wav" file

and after downloading it, it playsPlaySound("\\Files\\\example.wav");

-------------------------------------------------

But the meaning of this function ??? I don't think it makes any sense!

Alexsandr,

that's great, thanks! But the wav file should be generated by the TTS engine (TextToSpeech)

 
Nikolai Karetnikov:

Alexsandr,

All great, thanks! But the wav file should be generated by TTS engine (TextToSpeech)

I got it - it should work ???

Синтез в реальном времени
Отправив текст для синтеза, ваш сервис или приложение сразу же получит в ответ аудиозапись: задержка настолько мала, что позволяет создавать программное обеспечение с потоковым воспроизведением.

Photo by

here's something similarhttps://cloud.yandex.ru/docs/speechkit/tts/request

 
Nikolai Karetnikov:

...

Summarising

1. The syntax is still a mystery to me. Only managed to authenticate to the server, attempts to add other headers have failed so far

2. i wonder if WebRequest receives stream with sprinkles, or i'm writing it to a file incorrectly, but the .ogg file format obtained from char array result using WebRequest method is incorrect.

Rotten tomatoes welcome!

Let's think logically. Alexander showed that the script downloads and plays the file from the other server normally. Hence, webrequest is set up correctly. The only problem is the specifics of IBM's server. The peculiarities of their responses to requests.
Reason: