我的第一个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;interfaceusesWinapi.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;typeTForm2 = 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;varForm2: TForm2;implementationuses System.json;{$R *.dfm}procedure TForm2.Button1Click(Sender: TObject); varJO, JData: TJSONObject;code: string;temp: string; beginRESTClient1.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' thenbegin// 解析具體數據JData := JO.Get('data').JsonValue as TJSONObject;temp := '解析的詳細數據' + #13#10;// ISPtemp := 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
總結
以上是生活随笔為你收集整理的我的第一个REST客户端程序!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用测试工具-----XCAP
- 下一篇: 破解小记