user3773203 user3773203 - 1 month ago 13
HTTP Question

Get HTTP status code in asynchronous way

I would like to get the HTTP status code before the end of my doPost method in Java. For example in Python there is

self.send_response(200)
, which sends the status in asynchronous way?

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*
*/
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//Final result object


//I want to send a http status code 200 before the task running

myThreadPool = Executors.newFixedThreadPool(2);
Future taskOne = myThreadPool.submit(new Runnable() {
@Override
public void run() {
try {
try {
// My first task
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

});

// Task two
.
.

Answer

I'm not totally sure what is the intention of the code you posted, but I can guess that you want some kind of asynchronous processing, so that you can send some data to client before request finishes?

For that refer to asynchronous servlets, as described for example here: https://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3

There is even good example which seems to be serving what, I assume, you would like to achieve:

@WebServlet("/foo" asyncSupported=true)
   public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse res) {
            ...
            AsyncContext aCtx = request.startAsync(req, res);
            ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
            executor.execute(new AsyncWebService(aCtx));
        }
   }

   public class AsyncWebService implements Runnable {
        AsyncContext ctx;
        public AsyncWebService(AsyncContext ctx) {
            this.ctx = ctx;
        }
        public void run() {
            // Invoke web service and save result in request attribute
            // Dispatch the request to render the result to a JSP.
            ctx.dispatch("/render.jsp");
   }
}