【发布时间】:2018-09-20 07:00:42
【问题描述】:
我正在尝试使用 volley 从服务器检索数据,但是当我第一次调用此方法时,我得到了服务器的响应,但该方法返回 null。如果我第二次调用它,我会得到最后一个响应。
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
如何在第一次调用方法时获得响应?
【问题讨论】:
-
很可能是因为函数在
data从 volley 回调中填充之前结束。
标签: java android http-headers android-volley