Delphi - 传递标头值给REST服务

6
我有一个REST服务。默认情况下,返回的JSON数据中所有的NULL都被消除了。这给我带来了困难,因此我需要添加一个请求头来改变这种行为。我需要添加的请求头是:Accept-Formatting: json-nulls=include 我已经能够从POSTMAN中使用以下格式使其正常工作。

enter image description here

我无法使我的应用程序正常工作。
我的应用程序有一个TRestClient、TRestResponse和TRestRequest。
我尝试将其添加为TRestClient和TRestRequest的参数。虽然REST服务返回数据,但空字段未显示,这告诉我我的格式(或与请求头相关的其他内容)不正确。应该在哪里以及如何添加?
感谢任何想法。

enter image description here


2
我觉得看起来没问题。你确定 Accept-Formatting 头部信息确实被发送了吗?就我个人而言,我不喜欢 Embarcadero 的 REST 框架。它使用起来过于复杂,而且相当容易出错。我建议换用另一个 REST 客户端。或者,只需使用像 Indy 的 TIdHTTP 这样的工具手动发送自己的 REST 请求,这样你就完全掌控了它。 - Remy Lebeau
@Remy,- 没有。我该怎么做? - user1009073
要么使用像Wireshark这样的数据包嗅探器来嗅探网络流量,要么让您的服务器记录它实际接收到的标头。 - Remy Lebeau
我曾经遇到过类似的问题,需要通过Access-Token头部提供GUID,并且需要添加poDoNotEncode选项,然后它就可以正常工作了。 - Toby Groves
2个回答

2
尝试直接从“工具”>“Rest调试器”中调用,如果一切正常,请将组件复制/粘贴到您的项目中,并手动更改某些参数。

示例:

enter image description here


1
您还应该为授权头设置[poDoNotEncode]选项,否则它将无法工作。 - Soon Santos
谢谢,Soon Santos的评论对我有用,我正在使用Delphi 10.2 Tokyo。 - federico__

1
如果您想以编程方式发送Firebase通知,可以尝试我使用的方法,这对我很有效。
{Send a notification to Firebase Messaging.

 @param Titulo Notification title
 @param Mensagem Notification message
 @param Page The page the user will be redirected after the notification is clicked Ex: `/home`}
function EnviarNotificacao(Titulo, Mensagem, Page: string): string;
var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;
  RESTResponse1: TRESTResponse;
  JsonBody, JsonNotification, JsonData, JsonResponse: TJSONObject;
begin
  RESTClient1 := TRESTClient.Create(nil);
  RESTRequest1 := TRESTRequest.Create(nil);
  RESTResponse1 := TRESTResponse.Create(nil);
  RESTRequest1.Client := RESTClient1;
  RESTRequest1.Response := RESTResponse1;
  RESTRequest1.Method := TRESTRequestMethod.rmPOST;
  RESTRequest1.Params.AddItem('Authorization', 'key=AAAd...', pkHTTPHEADER, [poDoNotEncode]);
  RESTClient1.BaseURL := 'https://fcm.googleapis.com/fcm/send';

  JsonBody := TJSONObject.Create;
  JsonNotification := TJSONObject.Create;
  JsonData := TJSONObject.Create;
  JsonNotification.AddPair('title', Titulo);
  JsonNotification.AddPair('body', Mensagem);
  JsonData.AddPair('click_action', 'FLUTTER_NOTIFICATION_CLICK');
  JsonData.AddPair('page', Page);

  JsonBody.AddPair('notification', JsonNotification);
  JsonBody.AddPair('data', JsonData);
  JsonBody.AddPair('to', '/topics/your_topic');

  RESTRequest1.AddBody(JsonBody);
  RESTRequest1.Execute;
  JsonResponse := RESTResponse1.JSONValue as TJSONObject;
  Result := JsonResponse.ToString;
end;

你还应该释放 TJSONObject,我没有这样做是因为我很匆忙。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接