我试图获得用户的Reddit首页。我已经通过Token Retrieval (code flow)成功收到了Auth Token。我已经设法通过Postman获得预期的JSON响应,但是使用Retrofit无法产生相同的结果。由于onFailure()在回调中被触发,因此请求似乎超时。我正在使用范围:identity,mysubreddits和read。
附加说明:当使用不足的范围并分别使用过期的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
邮差成功:
经过多次启动和停止,似乎随机获得200或调用onFailure()我在我的一个Retrofit模型类中发现了问题。 JSON response from Reddit包含一个可以是long或boolean的字段。我把它定义为我的java类中的一个布尔值,当它作为long返回时抛出了一个llegalStateException。
type name description
special edited false if not edited, edit date in UTC epoch-seconds
otherwise. NOTE: for some old edited comments on reddit.com, this will
be set to true instead of edit date.
*我不确定如何在java中处理这种类型的二元性,所以现在我已经注释掉了字段,代码按预期工作。