Browse DevX
Sign up for e-mail newsletters from DevX


Send Form Data from Java: A Painless Solution : Page 3

Sending multipart/form data from Java is a painful process that bogs developers down in protocol details. This article provides a simple, real-world solution that makes sending POST requests as simple as sending GET requests, even when sending multiple files of varying type.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Send POST Requests from Java
Using the GET request from Java is very easy. You just create a URL with the request and then get an input stream:

InputStream is = new URL("hi.iq/register?name=J.Doe&email=abuse@spamcop.com").getInputStream();

In most cases, servers that process POST requests won't reject your GET request. Still, sometimes you'll have to POST instead of GET, particularly when you upload a file. Wouldn't having a solution like the form from Example 2 be nice? The corresponding Java request could look like this:

InputStream serverInput = ClientHttpRequest.post( new java.net.URL("hi.iq/register"), new Object[] { "name", "J.Doe", "email", "abuse@spamcop.com", "test.txt", new File("C:\home\vp\tmp\test.txt") });

Unfortunately, so far no such solution exists.

The Solution: ClientHttpRequest
If you search the Internet, you will find some partial or complicated solutions for using POST requests in Java. The best commercial solution probably is JScape's HTTP(S) component. Its well-designed API covers everything specified in HTTP (see RFC 2068). Other solutions are either too weird and complicated (see Ronald Tschal

Vlad Patryshev is an R&D engineer at the Java Business Unit of Borland. He recently started the myjavatools.com project. by e-mail.
Thanks for your registration, follow us on our social networks to keep up-to-date