发送okhttp请求时:HTTP ERROR 405和invalid_client

问题描述 投票:0回答:1

我正在向网站提出请求。但是,我一直得到一个返回的{"error":"invalid_client"}的JSON。此外,当我导航到URL时,我通过Web浏览器发出请求,它显示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);
 }

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


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


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

java https oauth-2.0 request okhttp
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.