gpt4 book ai didi

java - 将 RestTemplate 交换转换为 okHttpClient 调用

转载 作者:行者123 更新时间:2023-12-01 17:50:24 25 4
gpt4 key购买 nike

我正在尝试用 OkHttpClient 替换 Spring Boot 应用程序中的 ResteTemplate。

这是我使用 Spring 的 RestTemplate 的代码:

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<?> httpEntity = new HttpEntity<>("grant_type=client_credentials&scope=" + config.getScope(), headers);

ResponseEntity<Token> resp = getRestTemplate(builder).exchange(
new URI(config.getTokenUrl()),
HttpMethod.POST,
httpEntity,
Token.class);

这是我尝试使用 OkHttpClient 映射该代码:

RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("body", "grant_type=client_credentials&scope=" + config.getScope())
.build();

Request request = new Request.Builder()
.header("Accept", "application/json")
.header("Content-Type", "application/x-www-form-urlencoded")
.url("http://" + config.getTokenUrl())
.post(requestBody)
.build();

OkHttpClient client = buildOkHttpClient();

Response response = client.newCall(request).execute();
Objects.requireNonNull(response.body()).close();

问题是我收到错误 Response{protocol=http/1.1, code=405, message=Method Not Allowed 。Http 方法是 POST,如 RestTemplate 中所示。

但我不确定应该如何映射/转换 HttpEntity<?> httpEntity = new HttpEntity<>("grant_type=client_credentials&scope=" + config.getScope(), headers);遵守OkHttp?也许错误就在这里?

感谢任何帮助!

最佳答案

检查this link和这个结构:

RequestBody requestBody = new FormBody.Builder()
.add("grant_type", "client_credentials")
.add("scope", config.getScope())
.build();

Request request = new Request.Builder()
.url("http://" + config.getTokenUrl())
.post(requestBody)
.build();

关于java - 将 RestTemplate 交换转换为 okHttpClient 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60805765/

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