您的位置:首页 > 其它

DataSnap的REST服务器ServerMethod参数编码问题

2010-10-11 18:04 603 查看
在delphi xe下测试REST Server,其中有个ReverseString服务器函数,就是把一个传入的字串翻转。用DataSnap调用是:

procedure TForm1.Button1Click(Sender: TObject);
var
  vC:TDBXCommand;
  P:TDBXParameter;
begin
  SQLConnection1.Params.Values['CommunicationProtocol'] := 'http';
  SQLConnection1.Params.Values['HostName'] := edDSServer.Text;
  SQLConnection1.Params.Values['Port'] := edDSPort.Text;
  SQLConnection1.Params.Values['DSAuthenticationUser'] := edUserName.Text;
  SQLConnection1.Params.Values['DSAuthenticationPassword'] := edPassowrd.Text;
  SQLConnection1.Open;

  vC:=SQLConnection1.DBXConnection.CreateCommand;
  vC.CommandType:= TDBXCommandTypes.DSServerMethod;
  vC.Text:='TServerMethods1.ReverseString';
  vC.Prepare;
  vC.Parameters[0].Value.SetString(Edit2.Text);
  vC.ExecuteUpdate;
  Edit1.Text:=vC.Parameters[1].Value.asString;
  vC.Free;
end;


然而用http get来调用时却要注意参数的编码:

procedure TForm1.Button2Click(Sender: TObject);
var
  vMS:TMemoryStream;
  B:TBytes;
  J:TJSONObject;
  S:string;
  vURL:string;
begin
  vMS:=TMemoryStream.Create;
  try
    vURL:='http://'+edDSServer.Text+':'+edDSPort.Text+'/datasnap/rest/TServerMethods1/ReverseString/';
    vURL:=vURL+ParamsEncode(Edit2.Text);
    IdHTTP1.Get(vURL,vMS);
    SetLength(B,vMS.Size);
    vMS.Position:=0;
    vMS.Read(B[0],vMS.Size);
    J:=TJSONObject.Create;
    J.Parse(B,0);
    Edit1.Text:=TJSONArray(J.Get(0).JsonValue).Get(0).Value;
    J.Free;
  finally
    vMS.Free;
  end;
end;


在对参数编码时,有两个现成的函数:

1、IdURI.pas的TIdURI.ParamsEncode

这个函数里面把需要转义的字符定义为: UnsafeChars: TIdUnicodeString = '*<>#%"{}|/^[]`'; {do not localize}
但是这样不够,这两个字符没有包括:/?,如果参数中有这些字符,结果就不对了,或者导致调用失败。修改这个函数把这两个字符加上,就可以了。



2、httpApp.pas的HTTPEncode

首先,这个函数的参数是ansistring,其次,里面把空格转成加号,不能满足需要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐