当您将请求添加到队列时,该请求就会被执行异步地。这意味着它的执行顺序与您读取它的顺序不同 - 它发生在另一个线程上,并最终在完成后返回。
protected Response<String> parseNetworkResponse(NetworkResponse response) {
System.out.println(response.headers.get("Set-Cookie")); (1)
phpsessid = response.headers.get("Set-Cookie"); (2)
return super.parseNetworkResponse(response);
}
这将返回body响应的内容 - 从我在代码中读到的内容来看,您似乎想返回“Set-Cookie”标头的值。你可以这样做:
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
String sessionId = response.headers.get("Set-Cookie");
com.android.volley.Response<String> result = com.android.volley.Response.success(sessionId,
HttpHeaderParser.parseCacheHeaders(networkResponse));
return result;
}
这会将“Set-Cookie”标头的值返回给您onResponse
method:
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
}
}
更好的想法可能是在创建成功/失败监听器时传递一个成功/失败监听器getSessionId
称呼。通过这种方式,您可以轻松地访问调用类中的结果:
public void getSessionId(Context context, final Response.Listener<String> successListener, Response.ErrorListener failureListener) {
RequestQueue queue = Volley.newRequestQueue(context); // This should be a singleton!
StringRequest sr = new StringRequest(Request.Method.GET, "any url",
successListener,
failureListener) {
@Override
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
String sessionId = response.headers.get("Set-Cookie");
com.android.volley.Response<String> result = com.android.volley.Response.success(sessionId,
HttpHeaderParser.parseCacheHeaders(networkResponse));
return result;
}
};
queue.add(sr);
}
Edit:
现在,您可以按如下方式调用它:
Login login = new Login();
login.getSessionId(this, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// You can access member variables from here.
// This will only get called after the network activity has happened!
phpsessid = response;
// All the work you need to do after your session ID has updated, you can put into a method and call it from here
// In your original example, this would be (4)
onSessionIdUpdated();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// We'll just ignore these for now - you should handle errors though!
}
});
// Anything you put here will happen immediately after the getSessionId call above, and notably *before* onResponse or onErrorResponse is called (ignoring potential race conditions here for now).