5

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

我可以使用 HTML 组件向外部站点发送 POST 请求<form>,但<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>

4

1 回答 1

7

不能<h:form>用于提交到另一台服务器。默认情况下<h:form>提交到当前请求 URL。此外,它会自动添加额外的隐藏输入字段,例如表单标识符和 JSF 视图状态。此外,它会更改由输入字段名称表示的请求参数名称。这一切都会使它不适合将其提交到外部服务器。

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


更新:根据评论,您的实际问题是您不知道如何处理从您要发布到的 web 服务获得的 zip 文件,并且您实际上正在寻找错误方向的解决方案。

只需继续使用 JSF<h:form>并使用其通常的客户端 API 提交到 Web 服务,一旦你得到了 ZIP 文件InputStream(请不要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();
}

也可以看看:

于 2013-02-05T17:01:48.417 回答