使用Ballerina发送POST请求获取Choreo令牌遇415错误求助
解决Ballerina请求Choreo Dev Portal令牌返回415错误的问题
问题根源
你的代码出现415错误的核心原因有两点:
- 错误地对整个form payload字符串做了URL编码,导致服务器无法识别正确的表单格式;
- 原payload中的换行和空格会被编码为
%0A、%20这类无效字符,进一步破坏了表单结构。
Postman能正常运行是因为它会自动处理表单参数的编码和格式,不会引入多余字符。
修正后的代码方案
方案1:使用Ballerina内置表单参数支持(推荐)
直接通过post方法的form参数传递键值对,Ballerina会自动处理编码和Content-Type设置,避免手动构造的错误:
import ballerina/http; import ballerina/io; public function main() returns error? { final http:Client clientEndpoint = check new ("https://sts.choreo.dev"); // 构造表单参数键值对,若subject_token含特殊字符可单独编码 map<string> formParams = { 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" }; http:Request request = new(); request.addHeader("Authorization", "Basic *****"); json resp = check clientEndpoint->post("/oauth2/token", body = formParams, headers = request.headers); io:println(resp.toJsonString()); }
方案2:修正原手动构造payload的写法
如果坚持手动构造表单字符串,需要移除多余换行空格,且仅对单个参数值编码:
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 encodedSubjectToken = check url:encode("*******", "UTF-8"); string payload = string`grant_type=urn:ietf:params:oauth:grant-type:token-exchange&subject_token=${encodedSubjectToken}&subject_token_type=urn:ietf:params:oauth:token-type:jwt&requested_token_type=urn:ietf:params:oauth:token-type:jwt`; request.setTextPayload(payload); request.addHeader("Authorization", "Basic *****"); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); json resp = check clientEndpoint->post("/oauth2/token", request); io:println(resp.toJsonString()); }
关键说明
- 对于
application/x-www-form-urlencoded类型的请求,服务器期望key1=value1&key2=value2格式的字符串,仅每个参数的value需要URL编码,而非整个字符串; - 使用Ballerina内置的表单参数传递方式(方案1)能最大程度避免格式错误,同时简化代码。
内容的提问来源于stack exchange,提问作者Thenusan Santhirakumar
相关产品推荐
相关产品推荐

