Delphi使用JSON解析调用淘宝IP地址库REST API 示例

时间:2023-03-09 02:52:01
Delphi使用JSON解析调用淘宝IP地址库REST API 示例

Delphi使用JSON解析调用淘宝IP地址库REST API 示例

淘宝IP地址库:http://ip.taobao.com,里面有REST API 说明。

Delphi XE 调试通过,关键代码如下:

  1. var
  2. IdHTTP: TIdHTTP;
  3. RequestURL: string;
  4. ResponseStream: TStringStream;
  5. JO, JData: TJSONObject;
  6. begin
  7. IdHTTP := TIdHTTP.Create(nil);
  8. IdHTTP.ReadTimeout := 0;
  9. IdHTTP.AllowCookies := True;
  10. IdHTTP.ProxyParams.BasicAuthentication := False;
  11. IdHTTP.ProxyParams.ProxyPort := 0;
  12. IdHTTP.Request.ContentLength := -1;
  13. IdHTTP.Request.ContentRangeEnd := 0;
  14. IdHTTP.Request.ContentRangeStart := 0;
  15. IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
  16. IdHTTP.Request.Accept := 'text/html, */*';
  17. IdHTTP.Request.BasicAuthentication := False;
  18. IdHTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
  19. IdHTTP.HTTPOptions := [hoForceEncodeParams];
  20. RequestURL := 'http://ip.taobao.com/service/getIpInfo.php?ip=' + edtIP.Text;
  21. ResponseStream := TStringStream.Create;
  22. IdHTTP.Get(RequestURL, ResponseStream);
  23. IdHTTP.Free;
  24. ResponseStream.Position := 0;
  25. Memo1.Text := ResponseStream.DataString;
  26. ResponseStream.Position := 0;
  27. JO := TJSONObject.ParseJSONValue(ResponseStream.DataString) as TJSONObject;
  28. JData := JO.Get('data').JsonValue as TJSONObject;
  29. leISP.Text := (JData.Get('isp').JsonValue as TJSONString).Value;
  30. leCountry.Text := (JData.Get('country').JsonValue as TJSONString).Value;
  31. leArea.Text := (JData.Get('area').JsonValue as TJSONString).Value;
  32. leRegion.Text := (JData.Get('region').JsonValue as TJSONString).Value;
  33. leCity.Text := (JData.Get('city').JsonValue as TJSONString).Value;
  34. JO.Free;
  35. ResponseStream.Free;
  36. end;

源代码下载:http://www.400gb.com/file/63073750