Delphi7访问Go语言REST实例

[email protected], 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函数

/// 
/// Post方式访问Rest服务
/// 
/// rest服务地址
/// 请求字符串
/// 响应字符串
/// 访问是否成功
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;

/// 
/// Get方式访问Rest服务
/// 
/// rest服务地址
/// 相应字符串
/// 访问是否成功
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;

你可能感兴趣的:(Delphi7访问Go语言REST实例)