android - 改造 - 不记名令牌
问题描述
我在我的项目中使用 Retrofit,我正在尝试完成一个带有 Bearer 令牌的获取请求。
在 API 文档(https://the-one-api.dev/documentation)中它说:
“您需要在向 api 发出的每个请求中将访问密钥作为不记名令牌发送。不记名令牌必须以以下格式包含在授权标头中:
授权:承载 your-api-key-123
...只有 /book 端点在没有身份验证的情况下可用。”
当我运行下面的代码时,它给出“HTTP 401 Unauthorized”。(不是在书籍请求中,而是在电影请求中)。我尝试了“授权:xxx”和“授权:承载 xxx”,都失败了(xxx = 我的令牌)。
接口:
interface LotrApi {
@GET("book")
suspend fun getBookList(): BookListDto
@GET("book/{id}/chapter")
suspend fun getBookChapterList(
@Path("id") id : String,
): BookChapterListDto
@GET("movie")
suspend fun getMovieList(
@Header("Authorization") authHeader : String
): MovieListDto
}
存储库:
class MovieRepository @Inject constructor(
private val api: LotrApi
) {
fun getMovies(header : String): Flow<Resource<List<Movie>>> = flow {
try {
emit(Resource.Loading<List<Movie>>())
val movies = api.getMovieList(header).MovieListDtoToMovieList()
emit(Resource.Loading<List<Movie>>(movies))
} catch (e: HttpException) {
emit(Resource.Error<List<Movie>>("Unexpected Error"))
} catch (e: IOException) {
emit(Resource.Error<List<Movie>>("Please check your internet connection"))
}
}
}
MovieListDto:
data class MovieListDto(
val docs: List<Movie>,
val limit: Int,
val offset: Int,
val page: Int,
val pages: Int,
val total: Int
)
fun MovieListDto.MovieListDtoToMovieList() : List<Movie> {
return docs
}