【问题标题】:TRESTRequest: Is it possible to use custom media types in a POST request?TRESTRequest:是否可以在 POST 请求中使用自定义媒体类型?
【发布时间】:2019-06-03 15:41:17
【问题描述】:

我们有一个 API 需要我们自己的供应商特定的内容类型,例如 application/vnd.xxxx.custom.custom-data+json,但通过查看 REST.Client 的源代码,它似乎总是默认为 REST.Types 中的 ContentTypes 之一,例如在分配 @987654322 时@ 在我的正文请求中,它将默认为 ctAPPLICATION_X_WWW_FORM_URLENCODED

我尝试将内容类型直接分配给 TRESTClient.ContentType 属性,但它会被 TRESTRequest.ContentType 值覆盖。我还添加了自定义内容类型作为 TRESTRequest 上的参数,它确实被识别但仍然在末尾附加 ctAPPLICATION_X_WWW_FORM_URLENCODED 导致无效的 mime 类型异常。

begin
  APIClient := TRESTClient.Create(API_URL);
  APIRequest := TRESTRequest.Create(nil);

  try
    JsonToSend := TStringStream.Create(strJson, TEncoding.UTF8);
    APIClient.Accept := 'application/vnd.xxxx.custom.custom-data+json';
    // Below line gets overwritten
    APIClient.ContentType := 'application/vnd.xxxx.custom.custom-data+json';
    APIRequest.Client := APIClient;
    APIRequest.Resource := 'ENDPOINT_URL';
    APIRequest.Accept := 'application/vnd.xxxx.custom.custom-data+json';

    APIRequest.AddParameter(
      'Content-Type',
      'application/vnd.xxxx.custom.custom-data+json',
      pkHTTPHEADER,
      [poDoNotEncode]
      );  // This includes the custom CT in the request but appends the preset one as well so in this case ctAPPLICATION_X_WWW_FORM_URLENCODED when ctNone is set

    APIRequest.AddBody(JsonToSend, ctNone);
    APIRequest.Method := rmPost;
    try
      APIRequest.Execute;
    except
      on E: Exception do
        ShowMessage('Error on request: '#13#10 + e.Message);
    end;
  finally
    JsonToSend.Free;
  end;
end;

对我来说,我希望有这样一种情况,如果在标题参数中提供了内容类型,它将使用指定的内容类型而不是任何预设的内容类型。但是,由于提供了未知的媒体类型,会引发 API 异常。 API 异常内容如下:

Invalid mime type "application/vnd.xxxx.custom.custom-data+json, application/x-www-form-urlencoded": Invalid token character ',' in token "vnd.xxxx.custom.custom-data+json, application/x-www-form-urlencoded"

我的理解是它正在识别我在参数中提供的自定义内容类型,但仍在该请求标头中附加来自 REST.Types 的预设内容类型之一,导致它失败。我希望它发送请求标头为application/vnd.xxxx.custom.custom-data+json 的正文,不包括application/x-www-form-urlencoded

【问题讨论】:

  • 我已经编辑了我的原始答案,其中包含有关如何处理 XE8 中存在的 TRESTClient 错误的选项。

标签: rest http delphi delphi-xe8


【解决方案1】:

显然TRestCLient 在您的场景中试图表现得过于聪明。但是,有一种常规的方法。关键是:

  1. 向请求正文添加不能是ctNonectMULTIPART_FORM_DATActAPPLICATION_X_WWW_FORM_URLENCODED 的单个内容。
  2. 使用自定义标头值覆盖Content-Type

示例代码:

uses
  System.NetConsts;

RESTClient1.BaseURL := 'https://postman-echo.com/post';
RESTRequest1.Method := rmPOST;
RESTRequest1.Body.Add('{ "some": "data" }', ctAPPLICATION_JSON);
RESTRequest1.AddParameter(sContentType, 'application/vnd.hmlr.corres.corres-data+json',
  pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.Execute;

回显服务的响应是:

{
  "args":{
  },
  "data":{
    "some":"data"
  },
  "files":{
  },
  "form":{
  },
  "headers":{
    "x-forwarded-proto":"https",
    "host":"postman-echo.com",
    "content-length":"18",
    "accept":"application/json, text/plain; q=0.9, text/html;q=0.8,",
    "accept-charset":"UTF-8, *;q=0.8",
    "content-type":"application/vnd.hmlr.corres.corres-data+json",
    "user-agent":"Embarcadero RESTClient/1.0",
    "x-forwarded-port":"443"
  },
  "json":{
    "some":"data"
  },
  "url":"https://postman-echo.com/post"
}

注意回显的标题,当然尤其是Content-Type。我在 Delphi 10.2 Tokyo 中测试了该示例,因此希望它也可以在 XE8 中使用。

编辑

您观察到的行为是 bug (RSP-14001),即 fixed in RAD Studio 10.2 Tokyo

有多种方法可以解决这个问题。仅举几例:

  1. 调整您的 API 以放弃次要 mime 类型。
  2. 如果您可以放弃TRestClient 提供的所有额外好处,请将您的客户端实现改为TNetHttpClient
  3. 升级到 RAD Studio 10.2+。
  4. Hack it!强烈建议不要使用此选项,但它可以帮助您更好地了解 TRestClient 的实施细节。

破解它的最简单方法是修补方法TCustomRESTRequest.ContentType(注意我们谈论的是具有单个参数的不变量)以返回参数的ContentType,如果它的AParamsArray参数包含单个类型的参数@ 987654339@。这将允许我们向ctNone 类型的请求添加正文,以便修补的方法也将返回ctNone,这将有效地防止将另一个值附加到Content-Type 标头。

另一个选项是修补方法 TRESTHTTP.PrepareRequest 以在推断请求的内容类型之前更喜欢自定义 Content-Type 标头。这是 BTW 在 RAD Studio 10.2 Tokyo 中修复后当前实现的工作方式。此逻辑也适用于其他标头 - AcceptAccept-CharsetAccept-EncodingUser-Agent。修补方法TRESTHTTP.PrepareRequest 稍微难以实现,因为它具有private 可见性。

最难的选择是修补 TWinHTTPRequest.SetHeaderValue 以丢弃次要内容类型值。这也是最危险的一个,因为它会影响应用程序中与 HTTP 相关的任何内容(依赖于THTTPClient)。修补类也很困难,但并非不可能,因为它完全隐藏在System.Net.HttpClient.Win.pasimplementation 部分中。这是一个巨大的耻辱,因为它还阻止您创建自定义子类。也许有一个很好的理由......谁知道;)

【讨论】:

  • 我已经尝试了上面的代码,但仍然没有运气。我在请求中的内容类型在我的自定义标头末尾附加了ctAPPLICATION_JSON,导致application/vnd.xxxx.custom.custom-data+json, application/json
  • 您描述的行为是在 Delphi 10.2 Tokyo 中修复的错误 (quality.embarcadero.com/browse/RSP-14001)。请参阅edn.embarcadero.com/article/44747 以供参考。我会为 XE8 添加一个解决方法,如果我能找到的话。
  • 考虑到 4 个给定的选项,我采用了黑客方法。我添加了一个新的 AddBody() 重载方法来接收 JSON 对象和 TRESTContentType 而不是 JSON 对象的单个参数。然后我还在TRESTContentType 中添加了自定义媒体类型作为新的枚举值。实际的库文件没有被修改,而是更多地被复制并保存为项目中的不同单元。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
  • 2012-04-21
  • 2017-03-29
  • 1970-01-01
相关资源
最近更新 更多