the*_*sap 1 delphi json rest-client delphi-xe5
我正在尝试从客户端使用 RESTClient(Delphi XE5,Windows 8)发送 JSON。但在服务器端,它作为文本/纯数据接收。
我正在尝试发送的 JSON:
{
"kind": "News",
"group": {
"id": "G01"
},
"title": "Latest News",
"content": "this is the latest news"
}
Run Code Online (Sandbox Code Playgroud)
在服务器端接收:
----------120515234155952
内容配置:表单数据;名称=“身体”
内容类型:文本/纯文本
内容传输编码:引用打印
{
"kind": "新闻",
“团体”: {
"id": "G01"
},
"title": "最新消息",
"content": "这是最新消息"
}
----------120515234155952
内容配置:表单数据;名称=“访问令牌”
内容类型:文本/纯文本
内容传输编码:引用打印
ya29.QQKUa6ZDsco2uDK2neuYdurolLF8LAPDjMZGTdF3bnDLOIgX1JQ8g-FxKtMLSF-gl=
MDY
----------120515234155952--
用于将 JSON 添加到 TRESTRequest 的代码:
var
........
RESTRequest : TESTRequest;
content : String;
........
begin
........
content:='{'+
' "kind": "News",'+
' "group": {'+
' "id": "G01"'+
' },'+
' "title": "Latest News",'+
' "content": "this is the latest news"'+
'}';
RESTRequest.Params.AddItem('body',content,TRESTRequestParameterKind.pkREQUESTBODY,[],ctAPPLICATION_JSON);
............
end;
Run Code Online (Sandbox Code Playgroud)
我尝试使用另一种没有变化的变体:
RESTRequest.AddBody(Content); RESTRequest.AddBody(TJSONObject.ParseJSONValue(Content)); RESTRequest.AddBody(TJSONObject.ParseJSONValue(Content),ctAPPLICATION_JSON); RESTRequest.AddBody(TJSONObject.ParseJSONValue(UTF8String(Content)),ctAPPLICATION_JSON); 我发现在执行DoPrepareRequestBody方法时(在 上找到unit REST.Client)TCustomRESTRequest只使用LParam.Name和LParam.Value调用MultipartPeerStream.AddFormField. 这意味着 contentType 始终为空,MultiPartPeerStream 将其转换为 text/plain。
有什么方法可以强制其内容类型为application/json?
您可以尝试使用 TJSONObject 来组成主体:
var
jsResponse: TJSONValue;
jsRequest: TJSONObject;
begin
jsRequest := TJSONObject.Create();
jsRequest.AddPair('UserName', lbledtUser.Text);
jsRequest.AddPair('Password', lbledtPwd.Text);
RESTRequest.AddBody(jsRequest);
jsRequest.Free();
RESTRequest.Execute();
jsResponse := RESTRequest.JSONValue;
Run Code Online (Sandbox Code Playgroud)
在服务器端,内容类型符合预期:
var
jsReq: TJSONValue;
...
begin
...
if (CompareText(Request.ContentType, 'application/json') = 0) then
begin
jsReq := TJSONObject.ParseJSONValue(s);
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12953 次 |
| 最近记录: |