Send Form Data from Java: A Painless Solution

Send Form Data from Java: A Painless Solution

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:

Name: email:

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.1Host: hi.iqUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126Accept: 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.1Accept-Language: en-us, en;q=0.50Accept-Encoding: gzip, deflate, compress;q=0.9Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66Keep-Alive: 300Connection: keep-alive

Example 2. POST Request
Now, let’s replace ‘GET’ with ‘POST’ in the form HTML tag:

Name: email:

In this case, the HTTP request sent to the server looks like this:

POST register.jsp HTTP/1.1Host: hi.iqUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126Accept: 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.1Accept-Language: en-us, en;q=0.50Accept-Encoding: gzip, deflate, compress;q=0.9Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66Keep-Alive: 300Connection: keep-aliveContent-Type: application/x-www-form-urlencodedContent-Length: 36name=J.Doe&email=abuse%40spamcop.com

Example 3. Multipart POST Request
If the form contains file upload, you have to add enctype=”multipart/form-data” to the form tag. Otherwise, the file won’t be sent:

Name: email: file:

This form will produce the following HTTP request when sent from Mozilla 5:

POST register.jsp HTTP/1.1Host: hi/iqUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.2) Gecko/20021126Accept: 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.1Accept-Language: en-us, en;q=0.50Accept-Encoding: gzip, deflate, compress;q=0.9Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66Keep-Alive: 300Connection: keep-aliveContent-Type: multipart/form-data; boundary=---------------------------29772313742745Content-Length: 452-----------------------------29772313742745Content-Disposition: form-data; name="name"J.Doe-----------------------------29772313742745Content-Disposition: form-data; name="email"abuse@spamcop.com-----------------------------29772313742745Content-Disposition: form-data; name="file-upload"; filename="test.txt"Content-Type: text/plaintest data with some high ascii: ¿Como estás?-----------------------------29772313742745--

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/[email protected]").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", "[email protected]",                                            "test.txt", new File("C:homevp	mp	est.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

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as