I want to send a post request using ballerina to get a access token from the Choreo Dev Portal. I am able to do it using postman. But unable to make it work in Ballerina code level. it gives 415 - unsupported media type error. Need some Help in Ballerina
import ballerina/http;
import ballerina/io;
import ballerina/url;
public function main() returns error? {
final http:Client clientEndpoint = check new ("https://sts.choreo.dev");
http:Request request = new();
string payload = string`grant_type=urn:ietf:params:oauth:grant-type:token-exchange&
subject_token=*******&
subject_token_type=urn:ietf:params:oauth:token-type:jwt&
requested_token_type=urn:ietf:params:oauth:token-type:jwt`;
string encodedPayload = check url:encode(payload, "UTF-8");
io:print(encodedPayload);
request.setTextPayload(encodedPayload);
request.addHeader("Authorization","Basic *****");
request.addHeader("Content-Type","application/x-www-form-urlencoded");
io:print(request.getTextPayload());
json resp = check clientEndpoint->post("/oauth2/token",request);
io:println(resp.toJsonString());
}
I was expecting an access token from Choreo Devportal for the particular application.
Change the
Content-type
header setting method fromaddHeader()
tosetHeader()
.The
request.setTextPayload(encodedPayload);
will set theContent-type
astext/plain
as the default content type header.Later
request.addHeader("Content-Type","application/x-www-form-urlencoded");
is executed. TheaddHeader()
method will append the new value to the same header in addition to the previously addedtext/plain
. But thesetHeader()
will replace the previously set header which is the correct way in this scenario.However better way is to pass the
Content-type
as the second param ofsetXXXPayload()
method.request.setTextPayload(encodedPayload, "application/x-www-form-urlencoded")
;