Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send HTTP POST request to external site using <h:form>

Tags:

jsf

primefaces

I want to send a HTTP post request to another server using <h:form> component.

I can send a POST request to an external site using HTML <form> component, but <h:form> component does not support this.

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

How can I achieve this with <h:form>?

like image 894
zura katsitadze Avatar asked Feb 05 '13 16:02

zura katsitadze


1 Answers

It's not possible to use <h:form> to submit to another server. The <h:form> submits by default to the current request URL. Also, it would automatically add extra hidden input fields such as the form identifier and the JSF view state. Also, it would change the request parameter names as represented by input field names. This all would make it insuitable for submitting it to an external server.

Just use <form>. You can perfectly fine use plain HTML in a JSF page.


Update: as per the comments, your actual problem is that you have no idea how to deal with the zip file as obtained from the webservice which you're POSTing to and for which you were actually looking for the solution in the wrong direction.

Just keep using JSF <h:form> and submit to the webservice using its usual client API and once you got the ZIP file in flavor of InputStream (please, do not wrap it a Reader as indicated in your comment, a zip file is binary content not character content), just write it to the HTTP response body via ExternalContext#getResponseOutputStream() as follows:

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

See also:

  • How to provide a file download from a JSF backing bean?
like image 98
BalusC Avatar answered Sep 20 '22 23:09

BalusC