I have tested POST function in PostMan to do POST function with body parameters as below:
Here is eBay’s document for this function:
HTTP method: POST
URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
HTTP headers:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic <B64-encoded-oauth-credentials>
Request body:
grant_type=authorization_code
code=<authorization-code-value>
redirect_uri=<RuName-value>
My first attempt was as follow:
function udxEBayExchangeAuthCodeForUserToken(AAuthCode: String; AIsProduction: Boolean): String;
var
xRequestBody: TStringStream;
begin
with objHTTP.Request do begin
CustomHeaders.Clear;
ContentType := 'application/x-www-form-urlencoded';
CustomHeaders.Values['Authorization'] := 'Basic ' + 'V2VpbmluZ0MtV2VpbmluZ0M';
end;
xRequestBody := TStringStream.Create('grant_type=' + 'authorization_code' + ','
+ 'code=' + 'v%5E1.1%23i%5E1%23f%5E0%23r%5E1%23I%5E3%23p%5E3' + ','
+ 'redirect_uri=' + 'myredirecturlnameinsandbox',
TEncoding.UTF8);
try
try
Result := objHTTP.Post('https://api.sandbox.ebay.com/identity/v1/oauth2/token', xRequestBody);
except
on E: Exception do
ShowMessage('Error on request: ' + #13#10 + e.Message);
end;
finally
xRequestBody.Free;
end;
end;
Second attempt tried with below code for Body
xRequestBody := TStringStream.Create('grant_type=' + 'authorization_code' + '&'
+ 'code=' + AAuthCode + '&'
+ 'redirect_uri=' + gsRuName,
TEncoding.UTF8);
Both attempts give HTTP/1.1 400 Bad Request.
I have done some searching in Stack Overflow, and this is the closest question. The only different part is body of POST.
Can anyone please advise me what is correct way to assign POST body part?
Thanks.
3
Answers
The preferred way to send an
application/x-www-form-urlencoded
request withTIdHTTP
is to use the overloadedTIdHTTP.Post()
method that takes aTStrings
as input. You are not sending yourTStringStream
data in the properapplication/x-www-form-urlencoded
format.You don’t need to use the
TIdHTTP.Request.CustomHeaders
property to setupBasic
authorization.TIdHTTP
has built-in support forBasic
, simply use theTIdHTTP.Request.UserName
andTIdHTTP.Request.Password
properties as needed, and set theTIdHTTP.Request.BasicAuthentication
property to true.Try this instead:
If you want to send your own
TStringStream
, try this instead:I was troubled by this problem, but the answer didn’t work very much. Later, I used packet capturing to see the actual content sent. For friends with the same problems.
If you use TNetHTTPClient you can use the "System.Net.Mime" unit to manage the multipart form data by HTTP Post and manage request too.
I use Delphi 10.4.2