使用<h:form> </h:form>将HTTP POST请求发送到外部站点

时间:2013-02-05 16:50:35

标签: jsf primefaces

我想使用<h:form>组件向另一台服务器发送HTTP post请求。

我可以使用HTML <form>组件向外部网站发送POST请求,但<h:form>组件不支持此功能。

<form action="http://www.test.ge/get" method="post">
    <input type="text" name="name" value="test"/>
    <input type="submit" value="CALL"/>
</form>

如何使用<h:form>实现此目的?

1 个答案:

答案 0 :(得分:7)

无法使用<h:form>提交给其他服务器。 <h:form>默认提交给当前请求URL。此外,它会自动添加额外的隐藏输入字段,例如表单标识符和JSF视图状态。此外,它将更改请求参数名称,如输入字段名称所示。这一切都将使其无法提交给外部服务器。

只需使用<form>即可。您可以在JSF页面中完美地使用纯HTML。


更新:根据评论,您的实际问题是您不知道如何处理从您正在发布的网络服务获取的zip文件实际上你正朝着错误的方向寻找解决方案。

继续使用JSF <h:form>并使用其通常的客户端API提交到webservice,并在获得InputStream风格的ZIP文件后(请不要将其包装为Reader如您的评论中所示,zip文件是二进制内容而非字符内容),只需通过ExternalContext#getResponseOutputStream()将其写入HTTP响应正文,如下所示:

public void submit() throws IOException {
    InputStream zipFile = yourWebServiceClient.submit(someData);
    String fileName = "some.zip";

    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    ec.responseReset();
    ec.setResponseContentType("application/zip");
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    OutputStream output = ec.getResponseOutputStream();

    try {
        byte[] buffer = new byte[1024];
        for (int length = 0; (length = zipFile.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        try { output.close(); } catch (IOException ignore) {}
        try { zipFile.close(); } catch (IOException ignore) {}
    }

    fc.responseComplete();
}

另见:

相关问题