下面是一些简单的 XE2 测试代码,使用 SuperObject(使用 Indy's TIdHTTP
)通过 HTTP Post 发送 JSON 数据:
procedure TFrmTTWebserviceTester.Button1Click(Sender: TObject);
var
lJSO : ISuperObject;
lRequest: TStringStream;
lResponse: String;
begin
// Next 2 lines for Fiddler HTTP intercept:
IdHTTP.ProxyParams.ProxyServer := '127.0.0.1';
IdHTTP.ProxyParams.ProxyPort := 8888;
lJSO := SO('{"name": "Henri Gourvest", "vip": true, "telephones": ["000000000", "111111111111"], "age": 33, "size": 1.83, "adresses": [ { "adress": "blabla", "city": "Metz", "pc": 57000 }, { "adress": "blabla", "city": "Nantes", "pc": 44000 } ]}');
lRequest := TStringStream.Create(lJSO.AsString, TEncoding.UTF8);
try
IdHTTP.Request.ContentType := 'application/json';
IdHTTP.Request.Charset := 'utf-8';
try
lResponse := IdHTTP.Post('http://127.0.0.1:8085/ttposttest', lRequest);
ShowMessage(lResponse);
except
on E: Exception do
ShowMessage('Error on request:'#13#10 + E.Message);
end;
finally
lRequest.Free;
end;
lJSO := nil;
end;
这是出去的数据:
POST http://127.0.0.1:8085/ttposttest HTTP/1.0
Content-Type: application/json; charset=utf-8
Content-Length: 204
Connection: keep-alive
Host: 127.0.0.1:8085
Accept: text/html, */*
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)
{"vip":true,"age":33,"telephones":["000000000","111111111111"],"adresses":[{"adress":"blabla","pc":57000,"city":"Metz"},{"adress":"blabla","pc":44000,"city":"Nantes"}],"size":1.83,"name":"Henri Gourvest"}
Receiver 是一个TWebAction
on a TWebModule
,带有处理程序:
procedure TWebModuleWebServices.WebModuleWebServicesTTPostTestAction(
Sender: TObject; Request: TWebRequest; Response: TWebResponse;
var Handled: Boolean);
var
S : String;
lJSO: ISuperObject;
begin
S := Request.Content;
if S <> '' then
lJSO := SO('{"result": "OK", "encodingtestcharacters": "Typed € with Alt-0128 Will be escaped to \u20ac"}')
else
lJSO := SO('{"result": "Error", "message": "No data received"}');
Response.ContentType := 'application/json'; // Designating the encoding is somewhat redundant for JSON (http://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean)
Response.Charset := 'utf-8';
Response.Content := lJSO.AsJSON;
Handled := true;
end; { WebModuleWebServicesTTPostTestAction }
它使用TIdHTTPWebBrokerBridge
:
FWebBrokerBridge := TIdHTTPWebBrokerBridge.Create(Self);
// Register web module class.
FWebBrokerBridge.RegisterWebModuleClass(TWebModuleWebServices);
// Settings:
FWebBrokerBridge.DefaultPort := 8085;
这是实际的响应:
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json; charset=utf-8
Content-Length: 92
{"encodingtestcharacters":"Typed\u20acwithAlt0128FollowedBy8364escaped\u8364","result":"OK"}