2

My software includes the function below for posting to URL. I'm using Sysinternals TCPView to see the connection. The connection is not closing after posting to URL. How should I change the code for immediate connection close?

function PostURL(const AURL: string; Parameters: TStrings): string;
var
  HttpClient: THttpClient;
  HttpResponse: IHttpResponse;
begin
  HttpClient := THTTPClient.Create;
  try
    HttpClient.ConnectionTimeout:=3000;
    HttpClient.ResponseTimeout:=3000;
    HttpResponse := HttpClient.Post(AURL, Parameters, nil, TEncoding.UTF8);
    Result := HttpResponse.ContentAsString();
  finally
    HttpClient.Free;
  end;
end;
mjn42
  • 830
  • 1
  • 8
  • 24
Xel Naga
  • 826
  • 11
  • 28

2 Answers2

5

This is a feature of WinHttp, it keeps TCP connections alive for some time to reuse them faster, you can disable it by disabling this option in request.

OptionValue := WINHTTP_DISABLE_KEEP_ALIVE;
WinHttpSetOption(RequestHandle, WINHTTP_OPTION_DISABLE_FEATURE, @OptionValue, sizeof(OptionValue));

But there is no easy way to set this option in Delphi THttpClient, to do it you'll have to copy System.Net.HttpClient.Win.pas and System.Net.HttpClient.pas to your project and modify System.Net.HttpClient.Win.pas to add this code

EugeneK
  • 2,164
  • 1
  • 16
  • 21
2

what about the following

 HttpClient.SetRequestHeader('Connection', 'close');
Justin
  • 927
  • 11
  • 24