Volley 使用 StringRequest 和 RequestFuture 进行阻塞同步调用



我有以下代码可以调用并接收xml。

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Do something with the response
                            Log.e(TAG, "response from RRSendCarerLocation = " + response);
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // Handle error
                            Log.e(TAG, "error: RRSendCarerLocation = " + error);

                        }
                    });

            rq.add(stringRequest);

.

我遇到的问题是,从活动调用时这工作正常,但我想从意图服务中使用 Volley。意图服务在工作完成后会自行销毁,因此 Volley 回调永远不会检索响应。

我发现的一个解决方案是使用 RequestFuture 并调用 .get() 来阻止线程。 我在下面有一个我在这里找到的例子。

我可以用凌空执行同步请求吗?

RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(), future, future);
requestQueue.add(request);
try {
            return future.get(30, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // exception handling
        } catch (ExecutionException e) {
            // exception handling
        } catch (TimeoutException e) {
            // exception handling
        }

.

我不想在服务器返回 xml 时使用 JSON。 我看过 StringRequest 类,但我看不到任何支持 RequestFuture 的东西。

http://griosf.github.io/android-volley/com/android/volley/toolbox/StringRequest.html

无论如何可以使用StringRequest代码使用RequestFuture的阻止功能返回xml

谢谢

这是

为了以防您没有找到最佳解决方案或任何遇到相同问题的帖子的人。如果您想将StringRequest与FutureRequest一起使用,您可以尝试以下解决方案。

// Setup a RequestFuture object with expected return/request type 
RequestFuture<String> future = RequestFuture.newFuture();
// organize your string request object
StringRequest request = new StringRequest(url, future, future);
// add request to queue
VolleySingleton.getInstance(context).addToRequestQueue(request);
try {
    // Set an interval for the request to timeout. This will block the
    // worker thread and force it to wait for a response for 60 seconds
    // before timing out and raising an exception
    String response = future.get(60, TimeUnit.SECONDS);
    // Do something with the response
    Log.e(TAG, "response from RRSendCarerLocation = " + response);
    return Result.success();
} catch (InterruptedException | TimeoutException | ExecutionException e) {
    e.printStackTrace();
    return Result.retry();
}

我使用Retrofit来处理这种类型的请求。它非常易于使用,并允许您发出两种类型的请求(同步和取消同步)http://square.github.io/retrofit/

最新更新