How to post HTML Form Data to the Server? [Java Code]
To post HTML form data to the server in URL-encoded format using Java, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the Java POST message. You also need to specify the data type using the Content-Type: application/x-www-form-urlencoded request header. You can also send HTML form data to the server using the HTTP GET method. In this case, HTML form data is passed in the URL as key/value pairs separated by ampersands (&), and keys are separated from values by equality (=). The Java code was automatically generated for the POST HTML Form example.
HTTP POST is one of the nine standard methods of the Hypertext Transfer Protocol. The POST method is used to post data to the server, upload files and images, and submit HTML forms. The HTTP POST method differs from HTTP GET and HEAD requests in that POST requests can change the server's state.
What is HTML Form?
A form is a section of an HTML document that contains controls such as text and password input fields, radio buttons, checkboxes, and a Submit button, enclosed in an HTML <form> tag. HTML forms collect user input and send it to a server for processing. Examples of HTML forms are login and image upload forms.
In HTTP, there are two ways to submit HTML forms to the server using the application/x-www-form-urlencoded and multipart/form-data content types. HTML forms can be submitted from browsers and from Java code.
Submitting HTML forms using the application/x-www-form-urlencoded media type. The application/x-www-form-urlencoded media type is mainly used for submitting short HTML forms as key-value pairs, for example, when authorizing a user using login/password forms.
HTML Login Form Request Example
POST /login HTTP/1.1
Submitting HTML forms using the multipart/form-data media type. The multipart/form-data media type is used by browsers when uploading binary data to the server (for example, when uploading multiple images). In this case, the form data is formatted as a sequence of parts separated by MIME boundaries.
Send the form data to the server using the XMLHttpRequest or fetch methods.
Submitting HTML Forms using the HTTP GET Method
In some cases, you can submit form data using the HTTP GET method. The form data is passed to the server as a series of name/value URL parameters, and you are limited to the maximum length of the URL. For browsers, the limit is around 2000 characters (browser dependent) for the Java code, there is no such limit, but your server may have its limitations. For example, the maximum length of an Apache URL is 8177 characters. Submitting HTML forms using the HTTP GET method is less secure because you pass URL parameters data.
Example of Sending an HTML Form using HTTP GET Method
GET /login?login=my_login&password=my_passowrd HTTP/1.1