advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Download the code for this article
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 4.4/5 | Rate this item | 12 users have rated this item.
Email this articleEmail this article
Send Form Data from Java: A Painless Solution (cont'd)
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();
advertisement

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är's HttpClient) or too literal to be useful (check out this post from JavaRanch).

Because of this lack of free, simple solutions, I had to develop my own (download the source code). It is of moderate complexity and has an obvious interface that I hope is both simple and relatively universal. It can be instantiated from a URL String, URL, or an already open URLConnection.

After a user creates an instance of ClientHttpRequest, the user can add request parameters and cookies. Cookies are an important part of a request, especially with servlets that use cookies to keep track of sessions.

One can add parameters one by one, using the following:


setParameter(String name, String value); 
setParameter(String name, File file); 
setParameter(String parametername, String filename, InputStream fileinput) 

Or set them all at once, using the following:


setParameters(Map parameterMap) 

or


setParameters(Object[] parameterArray). 

The following method sets parameter as a string value or as a file depending on the argument type:


setParameter(String parametername, Object parameterdata).

This method works the same way for cookies. One can add cookies one by one, using the following:


setCookie(String name, String value) 

Or set them all at once, using one of these:


setCookies(Map cookieMap)
setCookies(String[] cookieArray)

After the request is ready, the post() method posts the request and returns an input stream that will contain the server's response, the same way as in URL.getInputStream(). For convenience, additional post methods are available:


post(Map parameters); 
post(Object[] parameters); 
post(String[] cookies, Object[] parameters); 
post(Map cookies, Map parameters). 

The following group of static post methods does all of this in one fell swoop:


InputStream serverInput = post(URL url, Map parameters); 
InputStream serverInput = post(URL url, Map cookies, Map parameters); 
InputStream serverInput = post(URL url, String[] cookies, Object[] parameters); 
InputStream serverInput = post(URL url, Object[] parameters).

All these methods let the user post a complicated form and receive an input stream in one expression, like the one in Example 2 at the beginning of this article.

Answer to the Eternal Question
Now you know how an HTML form (GET or POST) gets passed to the server as an HTTP request and how you can reproduce this behavior in your Java program—without overloading it with protocol details. You could say this solution answers the eternal question: How can one call a servlet or JSP from another servlet or JSP?

Previous Page: Example 2. POST Request  


Vlad Patryshev is an R&D engineer at the Java Business Unit of Borland. He recently started the myjavatools.com project. by e-mail.
Page 1: IntroductionPage 3: Send POST Requests from Java
Page 2: Example 2. POST Request 
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES