Search code examples
javaapache-httpclient-4.xrestlet

Communication between war files using HttpClient


I have two war files, they both located on the same server. I want to use some API war1 presents in war2. I have been told to use Apache's HttpClient but I'm not sure how, I would like a push in the right direction.

suppose war1 is api.common-1.53.46.20150305-1042.war and I want to call a method getFormatedDate() in the class DateFormatter under the packege com.bo.api.common.utilities

If you have a solution using Restlet, it will suffice as well. As for now I'm in the beginning of my project.


Solution

  • You can't call method directly but you need to export something from the war with HTTP and call it from the other one.

    I don't know which technology you use for the first war (servlet directly, a framework above like Restlet, Spring MVC, JAX-RS frameworks, ...) but you need to expose your method through an HTTP method on a dedicated URI.

    Then code like below can be used to call it from the second war:

    ClientResource cr = new ClientResource("http://<same-domain>/war2-rootpath/dateformatter");
    Representation repr = cr.put(new StringRepresentation(...));
    StringRepresentation sRepr = new StringRepresentation(repr);
    String returnedText = sRepr.getText();
    

    My code is a bit generic since your question is a bit vague ;-)

    Edited

    I think that you can a path like /dates with a method POST. The latter would accept a payload that contains the data as long (time value) and would return the formatted date as a string. The corresponding server resource would be something like that:

    public class DateFormatterServerResource extends ServerResource {
        @Post
        public String formatDate(long time) {
            return DateFormatter.getFormatedDate(new Date(time));
        }
    }
    

    This server resource would be attach of the router of your application as described below:

    Router router = (...)
    router.attach("/dates", DateFormatterServerResource.class);
    

    Hope it helps you anyway. Thierry