【发布时间】:2018-06-05 18:22:03
【问题描述】:
我正在尝试获取用户的 Reddit 首页。我已经通过Token Retrieval (code flow) 成功收到了一个Auth Token。我已设法通过Postman 获得预期的 JSON 响应,但无法使用 Retrofit 产生相同的结果。由于回调中触发了 onFailure(),因此请求似乎超时。我正在使用范围:身份、mysubreddits 和阅读。
补充说明:当分别使用不足的范围和使用过期的 Auth Token 时,我收到了 401 和 403 响应以及下面的代码。
相关常量:
redditToken = (actual auth token String)
RedditConstants.REDDIT_BASE_URL_OAUTH2 = "https://oauth.reddit.com"
相关方法部分:
if (redditToken != null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RedditConstants.REDDIT_BASE_URL_OAUTH2)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer " + redditToken);
headers.put("User-Agent", RedditConstants.REDDIT_USER_AGENT);
Call<RedditFeed> call = api.getFeed(headers);
call.enqueue(new Callback<RedditFeed>() {
@Override
public void onResponse(Call<RedditFeed> call, Response<RedditFeed> response) {
Log.d("FINDME", "response "+ response.toString());
if (response.isSuccessful()) {
Log.d("FINDME", "response was a success! we got the feed!");
} else {
Log.d("FINDME", "responce was not successfull triggered");
}
}
@Override
public void onFailure(Call<RedditFeed> call, Throwable t) {
Log.d("FINDME", "onFailure called from populateRedditFeed");
}
});
} else {
Toast.makeText(this, "Please Login with Reddit", Toast.LENGTH_SHORT).show();
}
改造界面:
public interface Api {
@GET(".")
Call<RedditFeed> getFeed (
@HeaderMap Map<String, String> headers
);
}
日志结果:
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default
I/zygote: Do full code cache collection, code=123KB, data=105KB
After code cache collection, code=111KB, data=79KB
D/FINDME: onFailure called from populateRedditFeed
邮递员成功:
【问题讨论】:
-
在 onFailure 中打印 throwable,它会告诉你错误是什么。在此处发布,以便我们提供帮助
-
无需对代码进行任何修改。我现在得到了成功的回应。在我在星巴克之前,现在我正在使用我的家庭 WiFi,也许这与它有关。明天我会在星巴克再次测试以确认。
-
哈哈酷 :) 很高兴知道......我可以看到代码很好,因为你指出了 401 和 403 代码,我知道你知道身份验证令牌......为什么我问了关于可扔日志的问题,无论如何保留日志,它会对你有所帮助。
标签: java android retrofit reddit bearer-token