我正在尝试实现一个服务器端 API 方法,该方法允许将一批 API 请求作为单个请求的一部分执行,并将批处理中每个请求的响应包装到JSONArray
返回给客户端的 a 中。
本质上,客户端使用“批处理”参数调用服务器,如下所示:
[{method: "getStatus" userId: "5"}, {method: "addFriend", userId: "5", friendId: "7"}]
这指定了由两个 API 调用组成的批处理。我想要做的是执行每一个,并将响应组合成如下内容:
[{status: "success", status: "At work..."}, {status: "error", message: "Friend not found!"}]
为了执行批处理,我反复调用RequestDispatcher.include()
,如下所示:
String format = request.getParamter("format"); //carry the requested response format forward for each batched request
JSONArray batchResponse = new JSONArray();
RequestDispatcher dispatcher = request.getRequestDispatcher("/apiContext");
OverridableHttpRequest reusableRequest = new OverridableHttpRequest(request);
JSONArray requests = (JSONArray)JSONValue.parse(request.getParameter("batch"));
for (Object batchedRequest : requests) {
reusableRequest.reset(); //clear all params and attribs
//set the parameters to use for this request
JSONObject requestParams = (JSONObject)batchedRequest;
for (Object key : requestParams.keySet()) {
reusableRequest.setParameter(key.toString(), requestParams.get(key).toString());
}
reusableRequest.setParameter("format", format);
LOG.debug("including: /apiContext?" + reusableRequest.getQueryString());
//process the request as if it were received normally
dispatcher.include(reusableRequest, response); //FIXME: how to get the response data for this include into 'batchResponse'?
}
一切正常(所有批处理请求都已执行,服务器正确处理它们),但我不知道如何获取包含的响应,以便将其添加到结果数组中。
有任何想法吗?