总是得到无效的grant_type参数或缺少参数,但适用于邮递员

时间:2019-04-07 15:07:06

标签: java spring-boot keycloak

我正在尝试通过发布请求获取访问令牌。 我已经尝试过邮递员的要求,并且效果很好。 但是从我的应用程序尝试时出现错误

  

{错误:“ invalid_request”,错误描述:“无效的grant_type参数或缺少参数”}

这是我尝试过的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;
  

邮递员   enter image description here

1 个答案:

答案 0 :(得分:0)

我发现您的代码存在一个重大问题,我认为它可以很好地解释您的问题。您正在发送JSON,但仍在发送Content-Type标头,建议您发送表单数据。

由于您的邮递员示例正在发送表单数据,所以我假设这就是您想要做的。保持Content-Type标头不变,但将POST正文更改为表单数据。您拥有的方式,两者无法匹配。表单数据的正确结构不是JSON。

这里是有关如何使用RestAssured发送表单数据的现有文章:

How to send a Content-Type form-data request using rest assured?

总而言之,您希望将参数放入Map中,然后将该映射传递给请求构建器链中的formParams()方法。

相关问题