Delphi接口Post内Authorization传Bearer Token问题

本文介绍了在Delphi中通过IXMLHTTPREQUEST调用POST接口时如何添加BearerToken到Authorization头,并展示了包含编码替换的详细代码示例。
摘要由CSDN通过智能技术生成

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,'&lt;','<',[rfReplaceAll]);
      resBe := StringReplace(resBe,'&apos;','''',[rfReplaceAll]);
      resBe := StringReplace(resBe,'&quot;','"',[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;

  • 22
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值