使用HttpClient在war文件之间进行通信

时间:2015-03-10 15:38:26

标签: java apache-httpclient-4.x restlet

我有两个war文件,它们都位于同一台服务器上。 我想在war2中使用一些API war1。 我被告知要使用Apache的HttpClient,但我不确定如何,我想推进正确的方向。

假设war1为api.common-1.53.46.20150305-1042.war,我想在包装getFormatedDate()

下的班级DateFormatter中调用方法com.bo.api.common.utilities

如果你有使用Restlet的解决方案,它也足够了。至于现在,我正处于项目的开始阶段。

3 个答案:

答案 0 :(得分:2)

您无法直接调用方法,但需要使用HTTP从war中导出某些内容并从另一个中调用它。

我不知道您在第一次战争中使用了哪种技术(直接使用servlet,上面的框架如Restlet,Spring MVC,JAX-RS框架......)但是您需要通过HTTP方法公开您的方法专用的URI。

然后可以使用下面的代码从第二次战争中调用它:

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();

我的代码有点通用,因为你的问题有点模糊; - )

<强>被修改

我认为您可以使用方法/dates建立POST之类的路径。后者将接受包含数据长度(时间值)的有效负载,并将格式化日期作为字符串返回。相应的服务器资源就是这样的:

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

此服务器资源将附加应用程序的路由器,如下所述:

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

希望无论如何它会帮助你。 亨利

答案 1 :(得分:1)

我不会将webservices归类为初学者的概念,因此在潜入并尝试编写此代码之前,您可能需要进行一些研究。但是,正如您所要求的那样,这是正确的方向:http://docs.oracle.com/javaee/6/tutorial/doc/bnayn.html

答案 2 :(得分:1)

我使用 Restlet 解决了我的问题。

我将要展示的类包装为Restlet资源(此时他将作为服务器)。

另一方面,我使用ClientResource检索(在我的情况下为Get)我需要的数据。

服务器端:

@Get
public JSONObject getIp(JsonRepresentation j) throws JSONException {
    JSONObject request = j.getJsonObject();
    . . .
}

客户方:

ClientResource cr = new ClientResource("http://localhost:8111/");
Representation repr = cr.get();
. . .