我的第一个REST客户端程序!

Delphi:XE8

看了好几天的资料了,也没有弄出来一个REST程序,尝试了XE8中带的例子,也都没有搞懂。我在网上不断搜索,看是否能够找到适合自己的文章,希望能够做出来一个REST的小例子,万幸,终于弄出来一个了!

这个小程序是把IP地址发送到淘宝的REST API,得到淘宝IP库返回的解析结果,先看看运行效果吧!


这是一个REST客户端程序,既然自己暂时编不出来REST服务器,那么最简单就是找一个可以尝试的REST服务器,所以我用这种方法先编一个RESET客户端程序,对REST程序了解一下!我们先看看我这个小程序使用了哪些控件:


RESTClient1: TRESTClient;:是REST客户端管理类。

RESTRequest1: TRESTRequest;:负责REST请求相关的工作,处理请求用的参数等。

 RESTResponse1: TRESTResponse:负责REST请求返回的结果,HTTP状态码和返回结果等。

这个小程序的整个单元的源代码在下面:

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, Vcl.StdCtrls, REST.Client,
  Data.Bind.Components, Data.Bind.ObjectScope;

type
  TForm2 = class(TForm)
    RESTClient1: TRESTClient;
    RESTRequest1: TRESTRequest;
    RESTResponse1: TRESTResponse;
    Button1: TButton;
    Memo1: TMemo;
    Edit1: TEdit;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

uses System.json;

{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
var
  JO, JData: TJSONObject;
  code: string;
  temp: string;
begin

  RESTClient1.BaseURL := 'http://ip.taobao.com//service/getIpInfo.php?ip=' +
    trim(Edit1.Text);
  RESTRequest1.Execute;

  // 清理先前数据
  Memo1.Clear;

  Memo1.Lines.Add('请求时间:' + Formatdatetime('yyyy-mm-dd hh:mm:ss zzz', now)
    + #13#10);

  // 在memo中显示得到数据
  temp := temp + '原始数据:' + #13#10;
  temp := temp + RESTResponse1.Content + #13#10;
  Memo1.Lines.Add(temp);

  // 解析得到的JSON数据
  JO := TJSONObject.ParseJSONValue(RESTResponse1.Content) as TJSONObject;

  // 得到错误编号
  code := (JO.Get('code').JsonValue as TJSONString).ToString;

  if code = '0' then
  begin

    // 解析具体数据
    JData := JO.Get('data').JsonValue as TJSONObject;

    temp := '解析的详细数据' + #13#10;

    // ISP
    temp := temp + ' I S P:' + (JData.Get('isp').JsonValue as TJSONString)
      .ToString + #13;
    Memo1.Lines.Add(temp);

    // 国家
    temp := '国家:' + (JData.Get('country').JsonValue as TJSONString)
      .ToString + #13;
    Memo1.Lines.Add(temp);

    // 地区
    temp := '地区:' + (JData.Get('area').JsonValue as TJSONString).ToString + #13;
    Memo1.Lines.Add(temp);

    // 省份
    temp := '省份:' + (JData.Get('region').JsonValue as TJSONString)
      .ToString + #13;
    Memo1.Lines.Add(temp);

    // 城市
    temp := '城市:' + (JData.Get('city').JsonValue as TJSONString)
      .ToString + #13#10;
    Memo1.Lines.Add(temp);

  end;

end;

end.


源代码下载:

http://download.csdn.net/detail/sunylat/8781273


参考资料:

淘宝IP地址查询
http://ip.taobao.com/instructions.php

http://blog.csdn.net/maxwoods/article/details/24265667

http://www.cnblogs.com/xalion/p/3370459.html

http://blog.csdn.net/sunylat/article/details/41407945

原文地址:https://www.cnblogs.com/sunylat/p/6119065.html