Learn to use WinRT’s HttpClient with Delphi.
I’m investigating how to use WinRT with Delphi 10.3. In the Japanese blog I wrote, I mentioned some WinRT. This blog, I will write how to write WinRT’s HttpClient in Delphi 10.3. In Delphi 10.3, WinRT’s HttpClient is in Winapi.WebRT.pas. You need to incorporate it into “uses”.
uses
Winapi.WebRT;
Winapi.WebRT contains Http_IHttpClient and THttp_HttpClient. If you want to create an instance of HttpClient, write as follows.
procedure TForm1.Button1Click(Sender: TObject);
var
httpClient: Http_IHttpClient;
begin
httpClient := THttp_HttpClient.Create();
end;
When creating THttp_HttpClient, the instance side uses an interface called Http_IHttpClient. Below is the code to get the URL data using the GetAsync method of the Http_IHttpClient interface.
procedure TForm1.Button1Click(Sender: TObject);
var
httpClient: Http_IHttpClient;
ws1: TWindowsString;
hs1: HSTRING;
hs2: HSTRING;
url: IUriRuntimeClass;
res: IAsyncOperationWithProgress_2__Http_IHttpResponseMessage__Http_HttpProgress;
s1: String;
begin
httpClient := THttp_HttpClient.Create();
ws1 := TWindowsString.Create('https://mjeld.com/');
hs1 := ws1;
url := TUri.CreateUri(hs1);
res := httpClient.GetAsync(url);
Await(res, kansu);
hs2 := res.GetResults().Content.ReadAsStringAsync.GetResults;
s1 := TWindowsString.HStringToString(hs2);
Memo1.Clear;
Memo1.Lines.Append(s1);
end;
HSTRING is prepared as a variable. This is used when passing a string to WinRT. I used a Record type called TWindowsString to convert from Delphi String to HSTRING. It is in System.Win.WinRT. You need to pass the URL to the GetAsync method of HttpClient. Then use TUri to convert from HSTRING to IUriRuntimeClass. As for TUri, it is included in Winapi.Foundation, so use it.
This time, I introduced how to use WinRT’s HttpClient in Delphi 10.3. Other than that, the blog that wrote how to use WinRT is in Japanese, but I introduce some.