Reddit API 使用 OAuth2 认证机制,主要涉及两种授权方式:
这个错误通常发生在 OAuth2 认证过程中,当客户端请求令牌时提供的 grant_type
参数不被服务器支持或格式不正确。
Authorization
头或 Content-Type
头Reddit API 支持的 grant_type 包括:
client_credentials
(仅应用授权)password
(用户名/密码授权)authorization_code
(授权码授权)refresh_token
(刷新令牌)import okhttp3.*;
import retrofit2.*;
import retrofit2.converter.gson.GsonConverterFactory;
public class RedditAuthService {
private static final String BASE_URL = "https://www.reddit.com/api/v1/";
private static final String CLIENT_ID = "your_client_id";
private static final String CLIENT_SECRET = "your_client_secret"; // 如果是脚本应用则为空字符串
public interface RedditAuthApi {
@FormUrlEncoded
@POST("access_token")
Call<ResponseBody> getAccessToken(
@Field("grant_type") String grantType,
@Field("username") String username,
@Field("password") String password,
@Header("Authorization") String authHeader
);
}
public static void main(String[] args) {
// 创建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "YourAppName/0.1 by YourRedditUsername")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
})
.build();
// 创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
RedditAuthApi api = retrofit.create(RedditAuthApi.class);
// 创建Basic Auth头
String credentials = Credentials.basic(CLIENT_ID, CLIENT_SECRET);
// 调用API
Call<ResponseBody> call = api.getAccessToken(
"password", // grant_type
"your_username",
"your_password",
credentials
);
try {
Response<ResponseBody> response = call.execute();
if (response.isSuccessful()) {
System.out.println("Success: " + response.body().string());
} else {
System.out.println("Error: " + response.errorBody().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Authorization
头必须使用 Basic Auth,格式为 Basic base64(client_id:client_secret)
Content-Type
必须为 application/x-www-form-urlencoded
@FormUrlEncoded
@POST("access_token")
Call<ResponseBody> refreshAccessToken(
@Field("grant_type") String grantType,
@Field("refresh_token") String refreshToken,
@Header("Authorization") String authHeader
);
@FormUrlEncoded
@POST("access_token")
Call<ResponseBody> getAppOnlyAccessToken(
@Field("grant_type") String grantType,
@Header("Authorization") String authHeader
);
通过以上方法,您应该能够解决 Retrofit 与 Reddit API 交互时遇到的 unsupported_grant_type
错误。
没有搜到相关的文章