我试图用OkHttpClient替换春季启动应用程序中的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
如RestTemplate所示,Http方法是POST。

但是我不确定如何映射/转换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();

09-11 20:08