使用 Java Unirest 发布'x-www-form-urlencoded'实体



我使用javaUnirest来调用我的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()

);
}

我得到这个错误:

{"错误":"无效请求","错误描述":"缺少表单参数: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"}

您的身体似乎处于应用程序/x-www-form-urlencoded的错误形式

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

可以在这里找到一个例子

最新更新