【问题标题】:When sending okhttp request: HTTP ERROR 405 and invalid_client发送 okhttp 请求时:HTTP ERROR 405 和 invalid_client
【发布时间】:2019-07-10 04:40:54
【问题描述】:

我正在向网站发出请求。但是,我不断收到 {"error":"invalid_client"} 返回的 JSON。此外,当我导航到我通过网络浏览器发出请求的 URL 时,它会显示 HTTP ERROR 405

从我读到的那些错误可能意味着我的请求结构不正确。

根据 API 的文档,这是我正在尝试执行的请求类型的示例:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "client_secret={your_client_secret}&client_id={your_client_id}&code={your_authorization_code}&grant_type=authorization_code&redirect_uri={your_redirect_uri}");
Request request = new Request.Builder()
  .url("https://api.website.com/v2/oauth2/token")
  .post(body)
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();

据我所知,我应该做同样的事情,只是有点不同。


Here 是我的doInBackground 方法的Pastebin(我正在使用AsynchTask)。下面是比较适用的部分:

OkHttpClient client = new OkHttpClient();

// A section here gets strings from a JSON file storing values such as client_id

 RequestBody bodyBuilder = new FormBody.Builder()
  .add("client_secret", CLIENT_SECRET)
  .add("client_id", CLIENT_ID)
  .add("code", AUTHORIZATION_CODE)
  .add("grant_type", GRANT_TYPE)
  .add("redirect_uri", REDIRECT_URI)
  .build();
 System.out.println("Built body: " + bodyBuilder.toString());

 String mediaTypeString = "application/x-www-form-urlencoded";
 MediaType mediaType = MediaType.parse(mediaTypeString);
 RequestBody body = RequestBody.create(mediaType, requestbodyToString(bodyBuilder)); // See Edit 1

 Request request = new Request.Builder()
  .url(TARGET_URL)
  .post(body)
  .addHeader("content-type", mediaTypeString)
  .addHeader("cache-control", "no-cache")
  .build();

 try {
  System.out.println("Starting request.");
  Response response = client.newCall(request).execute();
  String targetUrl = request.url().toString() + bodyToString(request);
  System.out.println("request: " + targetUrl);
  String responseBodyString = response.body().string();
  System.out.println("response: " + responseBodyString);
  return responseBodyString;
 } catch (IOException ex) {
  System.out.println(ex);
 }

就像我说的,我不断收到返回的 JSON {"error":"invalid_client"},当我导航到 URL 时,我通过网络浏览器发出请求,它显示 HTTP ERROR 405


我很乐意提供您需要的更多信息。谢谢!


编辑 1:它的第二个参数曾经是“bodyBuilder.toString()”,但我更改了它,因为我意识到它实际上并没有发送正文。结果还是一样 - {"error":"invalid_client"}。现在使用的方法来自here

【问题讨论】:

    标签: java https oauth-2.0 request okhttp


    【解决方案1】:

    我知道它是什么——我实际上并没有将authentication_code 写入文件,只是将它添加到另一个 JSONObject。哎呀。 :)

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      相关资源
      最近更新 更多