gpt4 book ai didi

java - Spring WebClient : Passing username and password in request body to get a token

转载 作者:行者123 更新时间:2023-12-01 16:35:48 30 4
gpt4 key购买 nike

遵循 Spring WebClient 教程 here我正在尝试将请求正文中的用户名和密码(无基本身份验证)传递到 API 端点,因为它需要这些作为参数。

我已经在 Postman 中进行了测试,将用户名和密码作为正文中的单独字段提供,并将 contentType 设置为 application/x-www-form-urlencoded。这会导致获得预期的 token ,但是当我使用 WebClient 的实现打印出下面的响应时,它会打印:

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

|

TcpClient tcpClient = TcpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECTION_TIMEOUT_MILIS)
.doOnConnected(connection -> {
connection.addHandlerLast(new ReadTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
connection.addHandlerLast(new WriteTimeoutHandler(CONNECTION_TIMEOUT_MILIS, TimeUnit.MILLISECONDS));
});

WebClient client = WebClient.builder().baseUrl(BASE_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient))).build();


LinkedMultiValueMap<String, String> multiMap = new LinkedMultiValueMap<>();

multiMap.add("username", username);
multiMap.add("password", password);

BodyInserter<MultiValueMap<String, Object>, ClientHttpRequest> inserter = BodyInserters.fromMultipartData(multiMap);


WebClient.RequestHeadersSpec<?> request = client.post().uri(API_CALL_GET_TOKEN).body(inserter);


String response = request.exchange().block().bodyToMono(String.class).block();
System.out.println(response);

最佳答案

提供.accept(MediaType.APPLICATION_JSON)提供了响应:

WebClient client = WebClient.create();

LinkedMultiValueMap<String, String> credentials = new LinkedMultiValueMap<>();

credentials.add("username", username);
credentials.add("password", password);

String response = client.post()
.uri(BASE_URL + API_CALL_GET_TOKEN)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromFormData(credentials))
.retrieve()
.bodyToMono(String.class)
.block();

return response;

关于java - Spring WebClient : Passing username and password in request body to get a token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61951034/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com