Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

java - How to send asynchronous Http Response?

I have created a Rest API that takes a request and gives response to the client. But My API is dependent on a third party service, that instead of giving a response, give a callback to my other endpoint. In order to send the service I need to wait for the callback to be received. How can I achieve it?

My Rest API that needs to send the response.

@POST
//  @Produces(MediaType.TEXT_XML)
//  @Consumes(MediaType.TEXT_XML)
    public ConnectResponse connectAPI(String connectString, @Context HttpHeaders headers) {
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        for (Entry<String, List<String>> entry : headers.getRequestHeaders().entrySet()) {
            logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            for (String eachEntry : entry.getValue()) {
                logger.info("eachEntry " + eachEntry);
            }
        }
        logger.info("USSD received " + connectString);
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        logger.info("---------- in connect post request ----------------------");
        ConnectRequest requestObj = new ConnectRequest();
        try {
            if (connectString != null && connectString.startsWith("<")) {
                requestObj = marshallConnectRequest(connectString);
            } else {
                requestObj = convertKeyValueToObject(connectString);
            }

            logger.info("Request is " + requestObj);
        } catch (JAXBException e) {
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error("----------------- Error in UnMarshalling ----------");
            logger.error(e.getMessage(), e);
        }
        ConnectResponse connectResponse = new ConnectResponse();
        connectResponse.setSession(requestObj.getSessionid());
        connectResponse.setText("Hello");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        logger.info("---------- returning response ----------------------");
        return connectResponse;
    }

    public ConnectRequest marshallConnectRequest(String connectString) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(ConnectRequest.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return (ConnectRequest) jaxbUnmarshaller.unmarshal(new StringReader(connectString));
    }

    public ConnectRequest convertKeyValueToObject(String connectString) {
        return new ConnectRequest();
    }

Instead of sending a simple response object I want to wait for the callback to hit at the following API.

@Path("/rest")
public class RESTWebservice {
    /*
     * @Context private MessageContext messageContext;
     */
    final Logger logger = Logger.getLogger(RESTWebservice.class);

    @POST
    @Path("/sendResponse")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public ResponseJSON postQuestionnaire(RequestJSON requestJson) {
    // performing operations
}

Call flow : -

  1. Client will call connectAPI which will call a third party API.
  2. The third party API after processing above call will callback postQuestionnaire.
  3. The connectAPI will send response only when the callback at postQuestionnaire is received.
question from:https://stackoverflow.com/questions/65914313/how-to-send-asynchronous-http-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ideally this should be your flow

  1. Client will call connectAPI which will call a third party API.
  2. The third party API after processing above call will callback postQuestionnaire. ---> This should be done seperate thread using Callable Task using executor service. Then you will have Future<ResponseFromPOstQuestionnaire> returned from executor service submit call
  3. The connectAPI will send response only when the callback at postQuestionnaire is received. ---> Once you hacve Future object you can do wait on by calling .get() (this is blocking call) so it will wait for response to come then you can return the same response or modified respone back to client.

Example on how to use callable task with executor service is explain here -> https://www.journaldev.com/1090/java-callable-future-example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...