RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Send Form Data from Java: A Painless Solution

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.

ending simple GET requests from Java is extremely easy (be it an application or a servlet), but sending multipart forms, like when you upload files, is painful. The former can be done in one method call that does all the underground work. The latter requires explicitly creating an HTTP request, which may include generating multipart boundaries while being careful with the exact amount and selection of newlines (e.g., println() would not always do the right job).

This article provides a simple solution that will relieve the pain of sending form data (like POST requests) from Java in most real-world scenarios. The intention is to make POST requests as simple as GET requests, even when sending multiple files of varying type (archives, XML, HTML, plain text, etc.).

GET and POST Requests
The two main methods for sending form data to a Web server are GET and POST. This section demonstrates how each method works in three scenarios. (Do not try to reproduce these at home. The URLs and e-mail addresses are fake.)

Example 1. GET Request
The following form uses the GET method:

<form method="get" action="hi.iq/register.jsp">
  Name:  <input type="text" name="name" value="J.Doe">
  email: <input type="text" name="email" value="abuse@spamcop.com">
  <input type="submit">

It performs the same task as requesting the following URL: http:hi.iq/register.jsp?name=J.Doe&email=abuse%40spamcop.com

If you were using Mozilla 5.0, the following would be the HTTP request sent to the server:

GET register.jsp?name=J.Doe&email=abuse%40spamcop.com HTTP/1.1
Host: hi.iq
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,
video/x-mng,image/png,image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1 Accept-Language: en-us, en;q=0.50 Accept-Encoding: gzip, deflate, compress;q=0.9 Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66Keep-Alive: 300Connection: keep-alive

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date