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.
Visit https://developer.github.com/changes/2020-02-10-deprecating-auth-through-query-param for 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格式。
参考: