我正在尝试通过发布请求获取我的访问 token 。 我已经尝试过 postman 的请求,效果非常好。 但是当从我的应用程序尝试时,我收到错误
{error: "invalid_request", error_description: "Invalid grant_type parameter or parameter missing"}
这是我尝试过的java代码:
RestAssured.baseURI
="http://localhost:8180/auth/realms/acme/protocol/openid-
connect/token";
RequestSpecification request = RestAssured.given();
JSONObject requestParams = new JSONObject();
requestParams.put("grant_type", "password");
requestParams.put("username", "amineamine"); // Cast
requestParams.put("password", "amineamine");
requestParams.put("client_id", "app-backend-springboot");
requestParams.put("client_secret", "9a1707db-431d-437c-bb70-
0e5f5d61dcb0");
request.body(requestParams.toJSONString());
request.header("Content-Type", "application/x-www-form-urlencoded;
charset=UTF-8");
Response response = request.post();
int statusCode = response.getStatusCode();
System.out.println(response.print());
System.out.println("The status code recieved: " + statusCode);
System.out.println("Response body: " +
response.body().asString());
这些是导入的:
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.json.simple.JSONObject;
in postman enter image description here
最佳答案
我发现您的代码存在一个重大问题,我认为它可以很好地解释您的问题。您正在发送 JSON,但您正在发送一个 Content-Type header ,表明您正在发送表单数据。
由于您的 postman 示例正在发送表单数据,因此我认为这就是您想要做的。保留 Content-Type header 不变,但将 POST 正文更改为表单数据。按照你的方式,两者不匹配。表单数据的正确结构不是 JSON。
这里有一篇关于如何使用 RestAssured 发送表单数据的现有帖子:
How to send a Content-Type form-data request using rest assured?
总而言之,您希望将参数放入 Map 中,然后将该映射传递给请求构建器链中的 formParams()
方法。
关于java - 总是收到无效的 grant_type 参数或参数丢失,但适用于 postman ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560426/