Delphi TNetHTTPClient使用递归方式取所有分页数据
业务系统提供的一个查询数据接口,可以通过分页方式取得数据,如果一次性取得所有数据,将页大小增大即可,但如果数据太多怕会造成内存溢出。
综合考虑每次只取一个分页,分页数据不要太大,用递归方式来获取是比较合理的解决方案,当页码大到一个数量,取不出数据即结束递归。
具体的实践代码示例:
uses
System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent,
DateUtils,
System.JSON;
procedure httpGetCustomer(pageNum: Integer; pageSize: Integer);
var
xh: Integer;
s: String;
str: String;
url: String;
client: TNetHTTPClient;
// vParams: TStringList; // 参数
vParams: TStringStream; // 接收值
vResponse: IHTTPResponse; // 接收参数
jsonData: TJSONObject;
retData: String;
code: String;
jsonRetData: TJSONObject;
total: Integer;
jv: TJSONValue;
rows: TJSONArray;
jsonCustomer: TJSONValue; // TJSONObject;
json2: TJSONObject;
beginTime, endTime: String;
token: String;
begin
token:=httpGetToken();
beginTime := FormatDateTime('yyyy-MM-dd', incDay(now, 0));
endTime := FormatDateTime('yyyy-MM-dd', incDay(now, 1));
//组装接
url := 'http://localhost/sys/customer/list?pageNum=' + IntToStr(pageNum) + '&pageSize=' + IntToStr(pageSize) + '&beginTime=' + beginTime + '&endTime=' + endTime;
log('取列表URL');
log(url);
client := TNetHTTPClient.Create(nil);
vParams := TStringStream.Create(); // 接收值
try
client.SecureProtocols := [THTTPSecureProtocol.TLS12];
client.ContentType := 'application/json;charset=UTF-8';
client.CustomHeaders['Authorization'] := token;
// vResponse := client.Get(url, vParams);
vResponse := client.Get(url);
if vResponse.StatusCode = 200 then
begin
log('取得列表返回');
log('---------');
log(vResponse.ContentAsString);
log('---------');
retData := vResponse.ContentAsString;
if retData <> '' then
begin
jsonData := TJSONObject.ParseJSONValue(Trim(vResponse.ContentAsString)) as TJSONObject;
code := '';
code := jsonData.Get('code').JsonValue.Value;
if code = '200' then
begin
s := jsonData.Get('data').ToString;
log('取得列表');
log('---------');
if ((jsonData.GetValue('data') as TJSONObject).TryGetValue('rows', jv)) then
begin
// 如果rows节点不存在 会报异常的
rows := ((jsonData.GetValue('data') as TJSONObject).GetValue('rows') as TJSONArray); // 不可以多级???
if rows.Size <= 0 then
begin
// Showmessage('为空的列表');
log('已取完,为空的列表');
end;
log('取到数据数量:' + IntToStr(rows.Size));
if rows.Size > 0 then
begin
// getCustomersData(rows);
for jsonCustomer in rows do
begin
application.ProcessMessages;
xh := xh + 1;
//log(IntToStr(xh));
var
json6: TJSONObject := jsonCustomer as TJSONObject;
log(json6.GetValue('customerId').Value);
end;
//递归 继续取下一页
httpGetCustomer(pageNum + 1, pageSize);
end;
end;
end;
end;
end
else
begin
log('获取列表失败:' + IntToStr(vResponse.StatusCode));
log('获取列表失败原因:' + vResponse.StatusText);
end;
finally
client.Free;
vParams.Free;
end;
end;
效果
标签:begin,rows,end,TNetHTTPClient,递归,Delphi,vResponse,TJSONObject,log From: https://blog.51cto.com/u_12668715/8340846