suikhan@126.com, 2018-12-13 @ shijiazhuang
1、Go创建示例的Rest服务
package main
import (
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
)
func main() {
app := iris.New()
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
})
v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions)
{
v1.Get("/home", func(ctx iris.Context) {
ctx.WriteString("Hello from /home")
})
v1.Get("/about", func(ctx iris.Context) {
ctx.WriteString("Hello from /about")
})
v1.Post("/send", func(ctx iris.Context) {
ctx.WriteString("sent")
})
v1.Put("/send", func(ctx iris.Context) {
ctx.WriteString("updated")
})
v1.Delete("/send", func(ctx iris.Context) {
ctx.WriteString("deleted")
})
}
app.Run(iris.Addr(":8080"))
}
2、Delphi7创建窗体程序
窗体程序,增加两个按钮和两个Memo。
2.1 添加引用
uses msxml;
2.2 编写POST和GET函数
/// <summary>
/// Post方式访问Rest服务
/// </summary>
/// <param name="url">rest服务地址</param>
/// <param name="req">请求字符串</param>
/// <param name="resp">响应字符串</param>
/// <returns>访问是否成功</returns>
function RestPost(url, req : string; out resp : string) : Boolean;
var
rest : IXMLHTTPRequest;
begin
Result := True;
try
rest := CoXMLHTTPRequest.Create;
rest.open('Post', url, False, EmptyParam, EmptyParam);
rest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
rest.Send(req);
resp := (rest.responseText);
except
on e : Exception do
begin
resp := 'ERROR:' + e.Message;
Result := False;
end;
end;
end;
/// <summary>
/// Get方式访问Rest服务
/// </summary>
/// <param name="url">rest服务地址</param>
/// <param name="resp">相应字符串</param>
/// <returns>访问是否成功</returns>
function RestGet(url : string; out resp : string) : Boolean;
var
rest : IXMLHTTPRequest;
begin
Result := True;
try
rest := CoXMLHTTPRequest.Create;
rest.open('Get', url, False, EmptyParam, EmptyParam);
rest.Send('');
resp := (rest.responseText);
except
on e : Exception do
begin
resp := 'ERROR:' + e.Message;
Result := False;
end;
end;
end;
2.3 调用接口返回
procedure TForm1.btnPostClick(Sender: TObject);
var
resp : string;
begin
if RestPost('http://localhost:8080/api/v1/send/', Memo1.Text, resp) then
begin
ShowMessage('执行成功!');
end;
Memo2.Text := resp;
end;
procedure TForm1.btnGetClick(Sender: TObject);
var
resp : string;
begin
if RestGet('http://localhost:8080/api/v1/home/', resp) then
begin
ShowMessage('执行成功!');
end;
Memo2.Text := resp;
end;