1.Delphi调用POST接口时,使用IXMLHTTPREQUEST调用Post接口时,有时候三方会要求往Authorization传Bearer Token。找了很久资料都没找到,后来解决了。发个帖子记录一下,下回能够直接找。如下图所示,PostMan测试示例
2.具体代码实现
unit msxml;
function TFORM1.PostData(InPut: string; url: string; token: string): string;
var
? xml, resBe: string;
? xmlhttp: IXMLHTTPREQUEST;
begin
? Result := '';
? xmlhttp:=CoXMLHTTPREQUEST.Create;
? try
? ? try
? ? ? token := StringReplace(token,#13#10,'',[rfReplaceAll, rfIgnoreCase]);
? ? ? Showmessage('调用本地地址:' + url + ';调用入参=' + InPut+';token:'+token);
? ? ? xmlhttp.Open('post',Url,False,'',''); ? ? ?///QueryLockReport
? ? ? xmlhttp.setRequestHeader('Content-type', 'application/json'); ?//text/xml
? ? ? xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8'); ?//text/xml
? ? ? xmlhttp.setRequestHeader('Authorization:' ,'Bearer '+ Token );
? ? ? xml := WideString(InPut);
? ? ? xmlhttp.Send(xml);
? ? ? resBe := xmlhttp.responseText;
? ? ? resBe := StringReplace(resBe,'&','&',[rfReplaceAll]);
? ? ? resBe := StringReplace(resBe,'>','>',[rfReplaceAll]);
? ? ? resBe := StringReplace(resBe,'<','<',[rfReplaceAll]);
? ? ? resBe := StringReplace(resBe,''','''',[rfReplaceAll]);
? ? ? resBe := StringReplace(resBe,'"','"',[rfReplaceAll]);
? ? ? resBe := StringReplace(resBe,#13#10,'',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,#13,'',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,#10,'',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,'<?xml version="1.0" encoding="utf-8"?>','',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,'<string xmlns="http://www.winning.com.cn">','',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,'</string>','',[rfReplaceAll, rfIgnoreCase]);
? ? ? resBe := StringReplace(resBe,'<string xmlns="http://tempuri.org/">','',[rfReplaceAll, rfIgnoreCase]);
? ? ? Showmessage('调用平台出参='+resBe);
? ? ? Result := resBe;
? ? except
? ? ? on E: Exception do
? ? ? begin
? ? ? ? ?Showmessage('错误;'+e.message);
? ? ? end;
? ? end;
? finally
? ? xmlhttp := nil; // 释放
? end; ? ?
end;