android 我如何处理 volley 库中的 setRequestProperty

android how can I approach setRequestProperty in volley library

我正在使用 httpurlconnection class 现在我转向 volley 如何放置授权令牌

 HttpURLConnection connection = (HttpURLConnection) client._url.openConnection();
    connection.setRequestProperty("Authorization", "Bearer " + client.Token);

提前谢谢你

how can I approach setRequestProperty in volley library

在 Volley 库 HurlStack 中,我们可以通过使用它来设置 setRequestProperty 连接:

1. 通过扩展 HurlStack 创建一个 class class :

public class CustomHurlStack extends HurlStack {
    ...
    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {

       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       connection.setRequestProperty("Authorization", "Bearer " + client.Token);

        return connection;
      }
     }

2. 而当创建 RequestQueue 然后传递 CustomHurlStack class object:

RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), 
                                                       new CustomHurlStack());

以下是我在排球项目中经常做的事情:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
       Map<String, String> headers = new HashMap<>();
       headers.put("Content-Type", "application/json");
       headers.put("Authorization", "Bearer " + mAccessToken);
       return headers;
}

对于基本身份验证案例:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
       Map<String, String> headers = new HashMap<>();                
       String credentials = "username:password";
       String auth = "Basic "
                        + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
       headers.put("Content-Type", "application/json");
       headers.put("Authorization", auth);
       return headers;
}