Github OAuth app獲取使用者資訊介面禁用url引數,必須使用header
本文時間:2021-06-24,使用OKhttp 4.9.1
原來的請求方式:
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.github.com/user?access_token"+accessToken) .build();
如果此時建立一個access_token:abc,將其輸入瀏覽器,比如:https://api.github.com/user?access_token=abc
網頁會返回一個json格式的使用者資訊,但GitHub郵箱會收到deprecation warning,提示這種使用url引數的方法即將停用(2021年9月8日起停用):
was used as part of a query parameter to access an endpoint through the GitHub API:
https://api.github.com/user
Please use the Authorization HTTP header instead, as using the `access_token` query parameter is deprecated. If this token is being used by an app you don't have control over, be aware that it may stop working as a result of this deprecation.
Depending on your API usage, we'll be sending you this email reminder on a monthly basis for each token and User-Agent used in API calls made on your behalf.
Just one URL that was accessed with a token and User-Agent combination will be listed in the email reminder, not all.
Visithttps://developer.github.com/changes/2020-02-10-deprecating-auth-through-query-paramfor more information about suggested workarounds and removal dates.
開頭那段程式碼無法正確獲取使用者資訊:
{"message":"Requires authentication","documentation_url":"https://docs.github.com/rest/reference/users#get-the-authenticated-user"}
根據官方文件提示,使用以下程式碼:
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.github.com/user") .header("Accept","application/vnd.github.v3+json") .header("Authorization","token "+accessToken) .build();
成功返回Github 使用者資訊json格式。
參考: