如何使用Kotlin在排球请求中添加自定义标头

时间:2018-08-13 09:27:16

标签: android kotlin android-volley

我有一个代码Volley Code

 val queue = Volley.newRequestQueue(context)
 val stringRequest = StringRequest(Request.Method.GET, linkTrang,
            Response.Listener<String> { response ->
                mTextView.text = "Response is: " + response.substring(0,500));
            },
            Response.ErrorListener {  })
    {

    }
    queue.add(stringRequest)

如何在此设置称为授权的标头?

2 个答案:

答案 0 :(得分:1)

我能够使用以下方法在Kotlin中做到这一点:

    val linkTrang = "YOUR URL"

    val queue = Volley.newRequestQueue(this)

    val stringRequest = object: StringRequest(Request.Method.GET, linkTrang,
        Response.Listener<String> { response ->
            Log.d("A", "Response is: " + response.substring(0,500))
        },
        Response.ErrorListener {  }) 
    {
        override fun getHeaders(): MutableMap<String, String> {
            val headers = HashMap<String, String>()
            headers["Authorization"] = "Basic <<YOUR BASE64 USER:PASS>>"
            return headers
        }
    }

    queue.add(stringRequest)

重要的是在构造请求之前使用 object 关键字,以便能够覆盖getHeaders()方法。

答案 1 :(得分:-3)

public void requestWithHeaders() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://www.youwebsite.com";
    StringRequest postRequest = new StringRequest(Request.Method.GET, url, 
        new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        }, 
        new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                Log.d("ERROR","error => "+error.toString());
            }
        }
    ) {     
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError { 
                Map<String, String>  params = new HashMap<String, String>();  

                params.put("Content-Type", "application/json");

                return params;  
        }
    };
    queue.add(postRequest);

}