我有一个Android应用程序,它可以将多个数据同步到Java Servlet,并且需要在将更改提交到数据库之前确保将响应传递到Android设备。
现在的问题是用户发送请求,服务器进行一些更改,将其提交,然后将响应发送回用户。有时用户永远不会收到响应(网络不可靠),然后过一会儿用户再次发送相同的请求(现在我已经重复了数据)。
我不需要知道Android是否正确处理了响应,我只需要确保他收到了响应即可。
如何确保客户收到回复?
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = IOUtils.toString(request.getInputStream(), "UTF-8");
JSONObject dataJson = new JSONObject(data);
Transaction trx = new Transaction(true);
JSONObject responseJson = SyncService.processSync(trx, dataJson);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(responseJson.toString());
// Here the transaction to the database is commited regardless if the client receives response (no error thrown)
trx.commit();
trx.close();
}
答案 0 :(得分:0)
我可以按照以下方法建议您,最后一个是我的最爱:
因为您提到了不需要客户端解析响应,所以请在servlet的线程中执行您正在做的事情以更快地响应并且不阻塞客户端
new Thread(()->{
String data =
IOUtils.toString(request.getInputStream(), "UTF-8");
JSONObject dataJson = new JSONObject(data);
Transaction trx = new Transaction(true);
JSONObject responseJson = SyncService.processSync(trx, dataJson);
}).start();
使用etag跟踪android中的请求
不使用http,而是使用 GRPC 协议,该协议为您提供了android和服务器之间的双向连接