Android Networking API 添加不记名令牌

时间:2021-01-01 16:29:21

标签: java android firebase get

我正在尝试使用 Twitter API。我已经在邮递员中测试了端点,它为我提供了所需的正确响应。我在代码中遇到的问题是它返回一个 null 作为响应。我相信这是由于我错误地向这个 Android 网络 API 添加了不记名令牌。谁能帮帮我

public class TwitterUserLookUp extends AppCompatActivity {
RecyclerView recyclerView;
EditText userName;
Button search;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_twitter_user_look_up);
    recyclerView = findViewById(R.id.twitterRCV);
    userName = findViewById(R.id.twitterHandle);
    search = findViewById(R.id.userLookUp);
    AndroidNetworking.initialize(getApplicationContext());
    search.setOnClickListener(v -> {
        if (TextUtils.isEmpty(userName.getText())) {
            userName.setError("Twitter Handle is required.");
            userName.requestFocus();
        } else {
            searchFunctionality(userName.getText().toString().trim());
        }
    });
}

public void searchFunctionality(String name) {
    AndroidNetworking.get("https://api.twitter.com/2/users/by/username/" + name)
            .addPathParameter("pageNumber", "0")
            .addQueryParameter("limit", "3")
            .addHeaders("Authorization", "xx")
            .setTag("test")
            .setPriority(Priority.LOW)
            .build()
            .getAsString(new StringRequestListener() {
                @Override
                public void onResponse(String response) {
                    Log.i("Testing", response);
                    Toast.makeText(TwitterUserLookUp.this, "User details: " + response, Toast.LENGTH_LONG).show();
                }

                @Override
                public void onError(ANError anError) {
                    Log.i("test", "test" + anError.getMessage());
                    Toast.makeText(TwitterUserLookUp.this, "Error Occurred: " + anError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
}

}

2 个答案:

答案 0 :(得分:0)

我使用这种方式的api接口添加了Bearer令牌

@POST("..............")
Call<PostModel> postModel(............,
                          @Header("Authorization") String token);

然后使用

将您的令牌传递给接口

“Bearer”+yourToken

答案 1 :(得分:0)

我能够通过使用名为 volley 的 API 库解决我的问题。我个人更喜欢 Volley 而不是 Android 网络库,因为它更容易理解发生了什么。下面我可以用我的不记名令牌添加一个参数

public void searchFunctionality(String name) {
    final String url = "https://api.twitter.com/2/users/by/username/" + name;
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, response -> Log.i("The Response ", response), error -> {
        Log.i("fail", "error" + error.getMessage());
    }) {
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<>();
            params.put("Authorization","Bearer " + "XX");
            return params;
        }
    };
    queue.add(stringRequest);
}