如何为Volley请求设置自定义标头?目前,已经有一种方式来设置POST请求的主体内容。我有一个简单的GET请求,但我需要传递自定义标头。我不知道JsonRequest类是否支持这样做。它是否可能实现?
如何为Volley请求设置自定义标头?目前,已经有一种方式来设置POST请求的主体内容。我有一个简单的GET请求,但我需要传递自定义标头。我不知道JsonRequest类是否支持这样做。它是否可能实现?
那是我的代码,别忘了 = 对象:如果不放就不起作用
val queue = Volley.newRequestQueue(this)
val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
// Request a string response from the provided URL.
val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener { response ->
txtPrueba.text = "Response: %s".format(response.toString())
},
Response.ErrorListener { txtPrueba.text = "That didn't work!" }
)
{
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers.put("Content-Type", "application/json")
return headers
}
}
queue.add(jsonObjectRequest)
试一下这个
public void VolleyPostReqWithResponseListenerwithHeaders(String URL,final Map<String, String> params,final Map<String, String> headers,Response.Listener<String> responseListener) {
String url = URL;
Log.i("url:", ":" + url);
StringRequest mStringRequest = new StringRequest(Request.Method.POST,
url, responseListener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
//Log.d("Error.Response", error.getLocalizedMessage());
}
}){
@Override
protected Map<String, String> getParams() {
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
};
mStringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mStringRequest.setShouldCache(true);
// dialog.show();
SingletonRequestQueue.getInstance(context).addToRequestQueue(mStringRequest);
}
这是从Github示例中设置标头的代码:
StringRequest myReq = new StringRequest(Method.POST,
"http://ave.bolyartech.com/params.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws
com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);