【发布时间】:2021-05-20 16:56:49
【问题描述】:
我正在开发一种工具来集成两个系统,我需要一些有关 Delphi 和 Web 服务的帮助。
首先,我正在使用 Delphi 5.0 和 Indy 8.009B。我知道它们都是古老的,但这就是我现在必须处理的问题。
我遇到的第一个问题是关于检索令牌。但我设法通过找到正确的 DLL 文件来处理我的 Indy 的 IdHTTP 组件版本(顺便说一下 2004 版本)。
这是我的代码:
slParams := TStringList.Create;
sReturnWS := TStringStream.Create('');
cIntercept := TIdConnectionInterceptOpenSSL.Create(nil);
sParams := 'client_id=' + sIdClient + '&client_secret=' + sClientKey;
sURL := sUrlAut + '?' + sParams;
IdHTTP := TIdHTTP.Create(nil);
IdHTTP.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
cIntercept.SSLOptions.Method := sslvTLSv1;
IdHTTP.Request.Accept := '*/*';
IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded';
IdHTTP.Request.ContentEncoding := 'utf-8';
IdHTTP.Intercept := cIntercept;
IdHTTP.ProtocolVersion := pv1_0;
IdHTTP.Request.Connection := 'keep-alive';
IdHTTP.Request.AcceptEncoding := 'gzip, deflate, br';
try
IdHTTP.Post(sURL, slParams, sReturnWS);
sReturn := sReturnWS.DataString;
vJson := TlkJSON.ParseText(sReturn);
它就像一个魅力。但现在我目前停留在第二步,即通过承载令牌授权/身份验证向服务器发送接收到的令牌。我动态地创建了我应该发送到服务器的 json,顺便说一下,这是一个 HTTPS 安全服务器。 json 文件很好,我已经使用在线 json 验证器对其进行了测试,方法是将其从内存流保存到硬盘驱动器,并且我还使用 Postman 和 SoapUI 对其进行了测试,它可以正常工作并得到验证。但是当我尝试通过我的 Delphi 应用程序发送它时,我总是得到同样的错误:422 Unprocessable Entity 这让我发疯,因为我只能从服务器的响应中读取。它不像 Postman 或 SoapUI,我可以从服务器读取所有返回的消息。好吧,召唤它我相信我遇到了这个错误,因为我没有通过 Delphi 正确设置一些必要的授权;无论如何,这是我发送 json 文件的代码(json 是我的包含 json 数据的字符串变量):
JsonToSend.WriteBuffer(Pointer(Json)^, Length(Json));
JsonToSend.Position := 0;
cIntercept := TIdConnectionInterceptOpenSSL.Create(nil);
try
IdHTTPAux.Intercept := cIntercept;
IdHTTPAux.Request.Clear;
IdHTTPAux.Request.ContentType := 'application/json';
IdHTTPAux.Request.ContentEncoding := 'UTF-8';
IdHTTPAux.Request.ExtraHeaders.Clear;
IdHTTPAux.Request.ExtraHeaders.FoldLines := False;
IdHTTPAux.Request.WWWAuthenticate := 'Bearer TOKEN';
idHTTPAux.Request.ExtraHeaders.Values['Cache-Control'] := 'no-cache';
IdHTTPAux.Request.ExtraHeaders.Values['Authorization'] :=
Uppercase(copy(sTokenType,1,1)) + copy(sTokenType,2,length(sTokenType)-1) + ' ' +
sToken;
IdHTTPAux.Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
cIntercept.SSLOptions.Method := sslvTLSv1;
IdHTTPAux.Request.Accept := '*/*';
IdHTTPAux.ProtocolVersion := pv1_0;
IdHTTPAux.Request.Connection := 'Keep-Alive';
IdHTTPAux.Request.AcceptEncoding := 'gzip, deflate, br';
try
IdHTTPAux.Post(sUrl, JsonToSend, sResponse);
请有人帮助我,因为我被困了好几天,我已经尽我所能尝试了一切,但我不知道该怎么办了。
【问题讨论】:
-
通常您会遇到授权问题,您会期望得到
401 Unauthorized响应。但422表示 Json 消息格式正确,但包含一些它不理解的内容。所以可能编码有问题:因为你说它是UTF8位基本上Delphi 5字符串类型只是Ansi(所以可能使用了一些无效字符/不支持的字符)。 -
我解决了。感谢您的回答。
标签: json rest delphi indy idhttp