【发布时间】: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