【问题标题】:Post an 'x-www-form-urlencoded' entity with Java Unirest使用 Java Unirest 发布一个 \'x-www-form-urlencoded\' 实体
【发布时间】:2022-09-28 02:43:31
【问题描述】:

我使用 java Unirest 来调用我的 api。但现在我需要发布一个对象,但使用 x-www-form-urlencoded,我使用以下代码:

public static void main(String[] args) {
        Unirest.config().setObjectMapper(new JacksonObjectMapper());
        System.out.println(Unirest
                .post(\"http://192.168.2.157:8082/auth/realms/collatum/protocol/openid-connect/token\")
                .header(\"Content-Type\", \"application/x-www-form-urlencoded\")
                .body(RequestToken.builder()
                        .username(\"user\")
                        .password(\"1234\")
                        .grant_type(\"password\")
                        .client_id(\"front\")
                        .build()).asString().getBody()


        );
    }

我得到这个错误:

{\"error\":\"invalid_request\",\"error_description\":\"缺少表单参数:grant_type\"}

当我分析请求时,标头没问题:(但看起来对象在 json 中并且没有 x-www-form-urlencoded

POST /auth/realms/collatum/protocol/openid-connect/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
user-agent: unirest-java/3.1.00
accept-encoding: gzip
Content-Length: 87
Host: 192.168.2.157:8082
Connection: Keep-Alive

{\"grant_type\":\"password\",\"client_id\":\"front\",\"username\":\"user\",\"password\":\"1234\"}HTTP/1.1 400 Bad Request
Cache-Control: no-store
X-XSS-Protection: 1; mode=block
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
Referrer-Policy: no-referrer
Date: Thu, 20 Jan 2022 13:56:53 GMT
Connection: keep-alive
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Content-Type: application/json
Content-Length: 84

{\"error\":\"invalid_request\",\"error_description\":\"Missing form parameter: grant_type\"}

    标签: java unirest unirest-java


    【解决方案1】:

    看起来您的身体的 application/x-www-form-urlencoded 格式错误。

    它不应该是一个 json 对象,而应该是类似于 grant_type=password&client_id=front&username=user&password=1234

    一个例子可以在这里找到 https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST#example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 2018-12-25
      • 2021-03-14
      • 2017-02-13
      相关资源
      最近更新 更多