无法使用 Fabric 在 Twitter 中获取关注者列表
Can't get List of followers in Twitter using Fabric
我正在使用 Fabric sdk for Twitter。在这里,我可以按照其文档中的描述发出登录请求。现在我不想获取登录用户的关注者列表,并在 RecycleView
中显示关注者姓名和个人资料图片。我尝试了各种解决方案,例如:
private void getFollowersdReq(long userID) {
showProgressDialog();
JsonObjectRequest getRegisterReq = new JsonObjectRequest(Request.Method.GET,
"https://api.twitter.com/1.1/followers/list.json?cursor=-1&&skip_status=true&include_user_entities=false&user_id=" + userID, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
LogUtils.LOGD("Server Response", response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("server Error",
"Error: " + error.getMessage());
Toast.makeText(getActivity(),
"Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(getRegisterReq, new SignpostUrlStack(twitterToken, secret));
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
在上面的代码中,我调用 Twitter API 来获取关注者列表,但在此我收到错误消息
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
我也试过了
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface CustomService {
@GET("/1.1/followers/list.json")
void show(@Query("user_id") Long userId,
@Query("screen_name") String var,
@Query("skip_status") Boolean var1,
@Query("include_user_entities") Boolean var2,
@Query("count") Integer var3, Callback<User> cb);
}
interface UsersService {
@GET("/1.1/users/show.json")
void show(@Query("user_id") Long userId,
@Query("screen_name") String screenName,
@Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
这样称呼 class:
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback<User>() {
@Override
public void success(Result<User> result) {
LogUtils.LOGI("Get success",result.toString());
}
@Override
public void failure(TwitterException e) {
hideProgressDialog();
}
});
通过这种方法我也无法获得所需的输出。
第二种方法(使用TwitterApiClient
)几乎是正确的,除了响应数据模型。有关响应的结构,请参阅 https://dev.twitter.com/rest/reference/get/followers/list。您需要根据此结构构建数据模型。
这是修复:
//data model
public class Followers {
@SerializedName("users")
public final List<User> users;
public Followers(List<User> users) {
this.users = users;
}
}
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {@GET("/1.1/followers/list.json")
void show(@Query("user_id") Long userId, @Query("screen_name") String
var, @Query("skip_status") Boolean var1, @Query("include_user_entities") Boolean var2, @Query("count") Integer var3, Callback < Followers > cb);
}
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback < Followers > () {@Override
public void success(Result < Followers > result) {
Log.i("Get success", "" + result.data.users.size());
}
@Override
public void failure(TwitterException e) {
}
});
上面的代码对我有用。希望对您有所帮助!
MyTwitterApiClient.java
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
/**
* Provide CustomService with defined endpoints
*/
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
// example users/show service endpoint
interface CustomService {
@GET("/1.1/followers/ids.json")
void list(@Query("user_id") long id, Callback<Response> cb);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";
private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";
TwitterLoginButton loginButton;
SharedPreferences shared;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics());
setContentView(R.layout.activity_main);
shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager()
.getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
//Here we get all the details of user's twitter account
System.out.println(result.data.getUserName()
+ result.data.getUserId());
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
@Override
public void success(Result<User> userResult) {
User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.
System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);
}
@Override
public void failure(TwitterException e) {
}
});
shared.edit().putString("tweetToken", token).commit();
shared.edit().putString("tweetSecret", secret).commit();
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback<String>() {
@Override
public void success(Result<String> result) {
// Do something with the result, which provides the
// email address
System.out.println(result.toString());
Log.d("Result", result.toString());
Toast.makeText(getApplicationContext(), result.data,
Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println(exception.getMessage());
}
});
MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {
@Override
public void failure(TwitterException arg0) {
// TODO Auto-generated method stub
}
@Override
public void success(Result<Response> arg0) {
// TODO Auto-generated method stub
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
System.out.println("Response is>>>>>>>>>"+result);
try {
JSONObject obj=new JSONObject(result);
JSONArray ids=obj.getJSONArray("ids");
//This is where we get ids of followers
for(int i=0;i<ids.length();i++){
System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to the login button.
loginButton.onActivityResult(requestCode, resultCode, data);
}
}
我正在使用 Fabric sdk for Twitter。在这里,我可以按照其文档中的描述发出登录请求。现在我不想获取登录用户的关注者列表,并在 RecycleView
中显示关注者姓名和个人资料图片。我尝试了各种解决方案,例如:
private void getFollowersdReq(long userID) {
showProgressDialog();
JsonObjectRequest getRegisterReq = new JsonObjectRequest(Request.Method.GET,
"https://api.twitter.com/1.1/followers/list.json?cursor=-1&&skip_status=true&include_user_entities=false&user_id=" + userID, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
LogUtils.LOGD("Server Response", response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("server Error",
"Error: " + error.getMessage());
Toast.makeText(getActivity(),
"Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(getRegisterReq, new SignpostUrlStack(twitterToken, secret));
// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}
在上面的代码中,我调用 Twitter API 来获取关注者列表,但在此我收到错误消息
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
我也试过了
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
public UsersService getUsersService() {
return getService(UsersService.class);
}
}
interface CustomService {
@GET("/1.1/followers/list.json")
void show(@Query("user_id") Long userId,
@Query("screen_name") String var,
@Query("skip_status") Boolean var1,
@Query("include_user_entities") Boolean var2,
@Query("count") Integer var3, Callback<User> cb);
}
interface UsersService {
@GET("/1.1/users/show.json")
void show(@Query("user_id") Long userId,
@Query("screen_name") String screenName,
@Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
这样称呼 class:
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback<User>() {
@Override
public void success(Result<User> result) {
LogUtils.LOGI("Get success",result.toString());
}
@Override
public void failure(TwitterException e) {
hideProgressDialog();
}
});
通过这种方法我也无法获得所需的输出。
第二种方法(使用TwitterApiClient
)几乎是正确的,除了响应数据模型。有关响应的结构,请参阅 https://dev.twitter.com/rest/reference/get/followers/list。您需要根据此结构构建数据模型。
这是修复:
//data model
public class Followers {
@SerializedName("users")
public final List<User> users;
public Followers(List<User> users) {
this.users = users;
}
}
class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
interface CustomService {@GET("/1.1/followers/list.json")
void show(@Query("user_id") Long userId, @Query("screen_name") String
var, @Query("skip_status") Boolean var1, @Query("include_user_entities") Boolean var2, @Query("count") Integer var3, Callback < Followers > cb);
}
new MyTwitterApiClient(session).getCustomService().show(userID, null, true, true, 100, new Callback < Followers > () {@Override
public void success(Result < Followers > result) {
Log.i("Get success", "" + result.data.users.size());
}
@Override
public void failure(TwitterException e) {
}
});
上面的代码对我有用。希望对您有所帮助!
MyTwitterApiClient.java
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterSession;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public class MyTwitterApiClient extends TwitterApiClient {
public MyTwitterApiClient(TwitterSession session) {
super(session);
}
/**
* Provide CustomService with defined endpoints
*/
public CustomService getCustomService() {
return getService(CustomService.class);
}
}
// example users/show service endpoint
interface CustomService {
@GET("/1.1/followers/ids.json")
void list(@Query("user_id") long id, Callback<Response> cb);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "YOUR_TWITTER_KEY";
private static final String TWITTER_SECRET = "YOUR_TWITTER_SECRET";
TwitterLoginButton loginButton;
SharedPreferences shared;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig), new Crashlytics());
setContentView(R.layout.activity_main);
shared = getSharedPreferences("demotwitter", Context.MODE_PRIVATE);
loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = Twitter.getSessionManager()
.getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
//Here we get all the details of user's twitter account
System.out.println(result.data.getUserName()
+ result.data.getUserId());
Twitter.getApiClient(session).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
@Override
public void success(Result<User> userResult) {
User user = userResult.data;
//Here we get image url which can be used to set as image wherever required.
System.out.println(user.profileImageUrl+" "+user.email+""+user.followersCount);
}
@Override
public void failure(TwitterException e) {
}
});
shared.edit().putString("tweetToken", token).commit();
shared.edit().putString("tweetSecret", secret).commit();
TwitterAuthClient authClient = new TwitterAuthClient();
authClient.requestEmail(session, new Callback<String>() {
@Override
public void success(Result<String> result) {
// Do something with the result, which provides the
// email address
System.out.println(result.toString());
Log.d("Result", result.toString());
Toast.makeText(getApplicationContext(), result.data,
Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println(exception.getMessage());
}
});
MyTwitterApiClient apiclients=new MyTwitterApiClient(session);
apiclients.getCustomService().list(result.data.getUserId(), new Callback<Response>() {
@Override
public void failure(TwitterException arg0) {
// TODO Auto-generated method stub
}
@Override
public void success(Result<Response> arg0) {
// TODO Auto-generated method stub
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(arg0.response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
System.out.println("Response is>>>>>>>>>"+result);
try {
JSONObject obj=new JSONObject(result);
JSONArray ids=obj.getJSONArray("ids");
//This is where we get ids of followers
for(int i=0;i<ids.length();i++){
System.out.println("Id of user "+(i+1)+" is "+ids.get(i));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
@Override
public void failure(TwitterException exception) {
// Do something on failure
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result to the login button.
loginButton.onActivityResult(requestCode, resultCode, data);
}
}