如何使用異步TNetHTTPClient?我嘗試了以下代碼,但它顯示錯誤。
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;
錯誤:
查詢標頭時出錯:所請求操作的句柄處于錯誤狀態
uj5u.com熱心網友回復:
在異步模式下,顧名思義,客戶端在后臺執行緒中異步運行請求。
執行以下代碼時,ContentAsString失敗,因為此時請求未完成。
output := httpclient.Get('https://google.com').ContentAsString
如果您想在異步模式下使用 HTTP 客戶端,則必須在請求完成后使用完成處理程式來運行適當的代碼。
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;
在異步模式下使用 HTTP 客戶端通常比從后臺執行緒在同步模式下使用它更復雜(特別是從記憶體管理方面)。
以下是使用匿名后臺執行緒的等效示例:
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;
當然,您也可以使用TTask或自定義執行緒來代替匿名執行緒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315622.html
