BSOne.SFC/eCrmHE/LIB_Common/HttpUtil.pas

95 lines
2.7 KiB
Plaintext

{*******************************************************}
{ }
{ HttpUtil }
{ }
{ Copyright (C) 2023 kku }
{ }
{*******************************************************}
unit HttpUtil;
interface
uses
IdHTTP, IdSSLOpenSSL, IdIOHandler, System.SysUtils, System.Classes;
const
POST_TIMEOUT = ':readTO';
function CreateHttpSSL(var aHttp: TIdHTTP; var aSSL: TIdSSLIOHandlerSocketOpenSSL;
nReadTO: Integer = 30000; nConnTO: Integer = 300000): Boolean;
function HttpPost(aHttp: TIdHTTP; sDest, sRqType, sParam: String; bUseTO: Boolean = false): String;
implementation
uses
Tocsg.Exception, Tocsg.Safe, IdExceptionCore;
function CreateHttpSSL(var aHttp: TIdHTTP; var aSSL: TIdSSLIOHandlerSocketOpenSSL;
nReadTO: Integer = 30000; nConnTO: Integer = 300000): Boolean;
begin
Result := false;
try
if (aHttp = nil) and (aSSL = nil) then
begin
aSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
aSSL.SSLOptions.Method := sslvSSLv23;
aSSL.SSLOptions.SSLVersions := [sslvTLSv1_2, sslvTLSv1_1, sslvTLSv1];
aHttp := TIdHTTP.Create(nil);
aHttp.IOHandler := aSSL;
with aHttp do
begin
Request.Clear;
Request.UserAgent := 'Mozilla/5.0';
Request.ContentType := 'application/json; charset=utf-8'; //'application/xml';
Request.Accept := 'application/json; charset=utf-8';
Request.Charset := 'utf-8';
Request.Connection := 'Keep-Alive';
Request.CustomHeaders.Values['Keep-Alive'] := 'timeout=300, max=100';
Request.CacheControl := 'no-store';
ConnectTimeout := nConnTO;
ReadTimeout := nReadTO;
end;
Result := true;
end;
except
on E: Exception do
ETgException.TraceException(E, 'Fail .. CreateHttpSSL()');
end;
end;
function HttpPost(aHttp: TIdHTTP; sDest, sRqType, sParam: String; bUseTO: Boolean = false): String;
var
ss: TStringStream;
begin
Result := '';
try
Guard(ss, TStringStream.Create(sParam, TEncoding.UTF8));
aHttp.Request.CustomHeaders.Values['requestType'] := sRqType;
Result := aHttp.Post(sDest, ss);
if (Result = '') and (aHttp.ResponseCode = 200) then
Result := 'true';
except
on E: EIdReadTimeout do
begin
if bUseTO then
begin
// _Trace('HttpPost() .. ReadTimeout ..');
Result := POST_TIMEOUT;
end;
exit;
end;
on E: Exception do
begin
{$IFDEF TRACE1}
ETgException.TraceException(Self, E, Format('Fail .. HttpPost(), RqType=%s', [sRqType]));
{$ENDIF}
end;
end;
end;
end.