android网络api添加承载令牌

t5zmwmid  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(334)

我正在尝试使用twitterapi。我在postman中测试了端点,它给出了我需要的正确响应。我在代码中遇到的问题是,它返回一个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();
                }
            });
}

}

mznpcxlj

mznpcxlj1#

我能够通过使用一个名为volley的api库来解决我的问题。我个人更喜欢凌空而不是安卓网络库,因为它更容易理解正在发生的事情。下面,我可以添加一个参数与我的持有人令牌

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);
}
wz1wpwve

wz1wpwve2#

我使用这个api接口添加了承载令牌

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

然后使用
“持票人”+你的代币

相关问题