首页 > 解决方案 > TRESTRequest:是否可以在 POST 请求中使用自定义媒体类型?

问题描述

例如,我们有一个 API 需要我们自己的供应商特定的内容类型,application/vnd.xxxx.custom.custom-data+json但是通过查看 REST.Client 的源代码,它似乎总是默认为 REST.Types 中的 ContentTypes 之一,例如ctNone在我的正文请求中分配时,它将默认为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+jsonexclude请求标头的正文application/x-www-form-urlencoded

标签: resthttpdelphidelphi-xe8

解决方案


AparentlyTRestCLient试图在你的场景中表现得太聪明。但是,有一种常规的方法。关键是:

  1. 将单个内容添加到请求正文中,该正文不能是ctNone,ctMULTIPART_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;

echo 服务的响应是:

{
  "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 中使用。

编辑

您观察到的行为是RAD Studio 10.2 Tokyo中修复的错误 (RSP-14001)

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

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

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

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

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


推荐阅读