如何在Android / Java中使用Google Volley for HTTP GET请求将响应头字段返回给main方法?

时间:2014-03-03 01:49:55

标签: android http-headers http-get android-networking android-volley

我在Android中使用谷歌凌空进行网络连接。我将发出一个http GET请求,并需要返回一个响应头值。我发现堆栈溢出的一些答案来访问头字段,但不知道如何将它返回到我的调用点。 请看看我的代码,我在其中放了四个数字来解释我的问题。

在(1)我可以打印出我需要的值。我试图将它保存在类属性(2)中,并且IDE中没有错误。如果我想从那里(3)返回它,我在(4)得到一个NullPointerException。也许它在那之前是一个读写问题。 那么我怎样才能得到(1)到(4)的值?非常感谢!

public class Login {

String phpsessid = null;

public Login() {}

public String getSessionId(Context context) {
    RequestQueue queue = Volley.newRequestQueue(context);
    StringRequest sr = new StringRequest(Request.Method.GET, "any url",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
        @Override
        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);
        }
    };
    queue.add(sr);
    return phpsessid; (3)
}

}

在main中:

Login login = new Login();
String result = login.getSessionId(this.getContext);
System.out.println(result);  (4)

1 个答案:

答案 0 :(得分:9)

向队列添加请求时,该请求将以异步方式执行 。这意味着它的执行顺序与您正在读取的顺序不同 - 它发生在另一个线程上,最终会在完成后返回。

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方法:

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);
}

编辑:

现在,您可以按如下方式调用:

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).