问题
I have to send a SOAP message to a WebService that needs basic authentication in the http request, but I can't find a way to do it.
After searching I found some solutions and workarounds, but none of them worked.
Here's my code:
procedure TMyForm.HTTPRIOHTTPWebNode1BeforePost(
const HTTPReqResp: THTTPReqResp; Data: Pointer);
var
UserName: string;
PassWord: string;
begin
UserName := 'aaa';
Password := 'bbb';
if not InternetSetOption(Data,
INTERNET_OPTION_USERNAME,
PChar(UserName),
Length(UserName)) then
raise Exception(SysErrorMessage(GetLastError));
if not InternetSetOption(Data,
INTERNET_OPTION_PASSWORD,
PChar(Password),
Length(Password)) then
raise Exception(SysErrorMessage(GetLastError));
end;
I tried setting the username and password in the HTTPRIO.HTTPWebNode, but it ignores them, and it doesn't rise the exceptions. The webservice keeps telling me that credentials are missing.
I managed to do it in c#
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
Byte[] credentialBuffer = new UTF8Encoding().GetBytes("aaa:bbb");
request.Headers.Add("Authorization", string.Format("Basic {0}", Convert.ToBase64String(credentialBuffer)));
return request;
}
but I can't find a way to do it in delphi.
Am I missing something or I'm doing it wrong?
I use DelphiXE8 with Firemonkey.
回答1:
Ok I did it thanks to the comments.
procedure TMyForm.HTTPRIOHTTPWebNode1BeforePost(
const HTTPReqResp: THTTPReqResp; Data: Pointer);
var
auth: String;
begin
auth := 'Authorization: Basic ' + idEncoderMIME1.EncodeString('aaa:bbb' );
HttpAddRequestHeaders(Data, PChar(auth), Length(auth), HTTP_ADDREQ_FLAG_ADD);
end;
I just add to the header 'Authorization: Basic ' + username:password encoded.
Actually I only did what I was doing in c#, but I couldn't figure it out before.
Thanks
回答2:
In newer version of Delphi (before 10.3 Rio)
procedure TClientSOAP.DoHTTPWebNodeBeforePost(
const HTTPReqResp: THTTPReqResp; Data: Pointer);
var
auth: String;
begin
auth := 'Authorization: Basic ' + TNetEncoding.Base64.Encode(FUserName + ':' + FPassword);
HttpAddRequestHeaders(Data, PChar(auth), Length(auth), HTTP_ADDREQ_FLAG_ADD);
end;
With 10.3 Rio you have to use mjn42 answer even if you have proxy
回答3:
For HTTP Basic Authentication, this code (placed before calling the SOAP service) should work:
HTTPRIO.HTTPWebNode.UserName := 'aaa';
HTTPRIO.HTTPWebNode.Password := 'bbb';
instead of the TMyForm.HTTPRIOHTTPWebNode1BeforePost
event handler
来源:https://stackoverflow.com/questions/34360581/soap-message-add-authentication-in-http-header