//Post
FHttp := TIdHttp.Create(nil);
FHttp.HTTPOptions := [];
FHttp.ProtocolVersion := pv1_1;
FHttp.Request.ContentType := 'application/x-www-form-urlencoded';
FHttp.Request.UserAgent := 'Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)';
FHttp.Request.Accept := '*/*';
FHttp.Request.Connection := 'close';
FHttp.ReadTimeout := 10000;
FHttp.ConnectTimeout := 3000;
//Get
FHttp2 := TIdHttp.Create(nil);
FHttp2.HTTPOptions := [];
FHttp2.ProtocolVersion := pv1_1;
FHttp2.Request.ContentType := 'application/json';
FHttp2.Request.UserAgent := 'Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)';
FHttp2.Request.Accept := '*/*';
FHttp2.Request.Connection := 'close';
FHttp2.ReadTimeout := 10000;
FHttp2.ConnectTimeout := 3000;
function TSOV.SendPostMessage(sUrl: string; paramlst: TStringList): string;
begin
Result := '';
if FHttp.Connected then //这样写的好处是 保障服务中途断开再连接 后的请求正常
FHttp.Disconnect;
try
try
Result := UTF8Decode(http.Post(sUrl, paramlst));
except
on e: Exception do
begin
result:= '';
//ShowMessage(e.Message);
end;
end;
finally
FHttp.Disconnect;这样写的好处是 保障服务中途断开再连接 后的请求正常
end;
end;
function TSOV.SendGetMessage(sUrl: string): string;
var
responseStream: TStringStream;
begin
Result := '';
if FHttp2.Connected then //这样写的好处是 保障服务中途断开再连接 后的请求正常
FHttp2.Disconnect;
responseStream := TStringStream.Create('');
try
try
http.Get(sUrl, responseStream);
Result := UTF8Decode(responseStream.DataString);
except
on e: Exception do
ShowMessage(e.Message);
end;
finally
FreeAndNil(responseStream);
FHttp2.Disconnect;//这样写的好处是 保障服务中途断开再连接 后的请求正常
end;
end;
XE版本下,线程带有TThread.CreateAnonymousThread方法。网上有人用来判定超时,用上面的例子修改了下,如下:
将方法执行添加到线程,添加for循环替代超时的功能,每次for循环sleep500,循环6次,就是3秒(忽略了Application.ProcessMessages的处理时间)。
function SendPostMessage(sMethod, sUrl: string; paramlst: TStringList; var sOut, sErr: string): Boolean;
begin
Result := False;
sOut:= '';
sErr:= '';
if FHttp.Connected then //这样写的好处是 保障服务中途断开再连接 后的请求正常
FHttp.Disconnect;
try
try
SystemLog('['+ sMethod+ '] Snd:'+ paramlst[0]);
TThread.CreateAnonymousThread(
procedure
begin
sRec := UTF8Decode(FHttp.Post(sUrl, paramlst));
end
).Start;
for I := 0 to 5 do
begin
if sRec<> '' then
begin
sOut:= sRec;
Break;
end;
Application.ProcessMessages;
TThread.Sleep(500);
Application.ProcessMessages;
end;
SystemLog('['+ sMethod+ '] Rec:'+ sOut);
if FHttp.Connected then
sRec:= 'shit';
Result:= True;
except
on e: Exception do
begin
//'Read Timeout'
sErr:= e.Message;
end;
end;
finally
FHttp.Disconnect;这样写的好处是 保障服务中途断开再连接 后的请求正常
end;
end;