簡體   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