How to use asynchronous TNetHTTPClient? I tried following code, but it shows error.
procedure TForm1.Button1Click(Sender: TObject);
var
httpclient: TNetHTTPClient;
output: string;
begin
httpclient := TNetHTTPClient.Create(nil);
try
httpclient.Asynchronous := True;
output := httpclient.Get('https://google.com').ContentAsString;
finally
httpclient.Free;
end;
end;
Error:
Error querying headers: The handle is in a wrong state for the requested operation
CodePudding user response:
In asynchronous mode, as the name implies, client runs request asynchronously in the background thread.
When following code is executed, ContentAsString
fails because request is not completed at that point.
output := httpclient.Get('https://google.com').ContentAsString
If you want to use HTTP client in asynchronous mode, you will have to use completion handlers to run appropriate code after request is completed.
procedure TForm1.Button1Click(Sender: TObject);
var
httpclient: TNetHTTPClient;
begin
httpclient := TNetHTTPClient.Create(nil);
httpclient.Asynchronous := True;
httpclient.OnRequestCompleted := HTTPRequestCompleted;
httpclient.Get('https://google.com');
end;
procedure TForm1.HTTPRequestCompleted(const Sender: TObject; const AResponse: IHTTPResponse);
var
output: string;
begin
output := AResponse.ContentAsString;
Sender.Free;
end;
Using HTTP client in asynchronous mode is generally more complicated (especially from the memory management aspect) than using it in synchronous mode from the background thread.
Following is equivalent example using anonymous background thread:
procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.CreateAnonymousThread(
procedure
var
httpclient: TNetHTTPClient;
output: string;
begin
httpclient := TNetHTTPClient.Create(nil);
try
httpclient.Asynchronous := False;
output := httpclient.Get('https://google.com').ContentAsString;
finally
httpclient.Free;
end;
end).Start;
end;
Of course, you can also use TTask
or custom threads instead of anonymous threads.