繁体   English   中英

发送okhttp请求时:HTTP错误405和invalid_client

[英]When sending okhttp request: HTTP ERROR 405 and invalid_client

我正在向网站提出请求。 但是,我不断收到返回的JSON {"error":"invalid_client"} 另外,当我导航到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();

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


是我的doInBackground方法的doInBackground (我正在使用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"} 现在使用的方法来自这里

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM