Posting Form Data with Java Client using java.net.URL Example
Posting Query Parameters using the URL and HttpURLConnection Class
In this example, we use java.net.URL to POST form data using query parameters to call web service and return results. The example provided is very succinct and describes everything in detail.
The URL class represents and Uniform Resource Locator — an address to a location on the internet to some resource whether it be a web page for your Web browser, a file for FTP or a service to produce or consume some data. The following URL shown below takes you to this post using the http protocol, hosted on www.avaldes.com domain, using port 8080, with this path or reference.
URL Structure

Common components of a URL
Although there can be more components in a URL, the most common form has four components detailed above. Additional components may include query parameters which are separated by a question mark (?) after the Path and each additional query parameter is separated by ampersand (&).
| Component | Description |
|---|---|
| Protocol | Every URL begins with the protocol or scheme. Common protocols include http, https, ftp, file, cvs, svn, mailto, ldap, or chrome all followed by colon (:) and two slashes (//). |
| Host | In my example, it is avaldes.com for my domain. Other domains include google.com, cnn.com, foxnews.com, whitehouse.gov, army.mil, and nyu.edu. Notice that domain names also contain a dot (.) and extension depending on the type of domain it is: com for company, org for organization, edu for education, mil for military, gov for government. |
| Port | Port at which the internet (web, ftp, ldap, etc) server is listening to for resource requests from clients. |
| Path | Web page or resource you are actually looking for. In this example, calling-restful-service-with-java-client-using-java-net-url-example is the web page we are seeking. |
Example using POST Request with Web Service
In this example, we will add a new book using POST method passing all form parameters as query parameters in my Java program. I am building that queryParam object using StringBuffer class and using append for each of the parameters and their corresponding values.
package com.avaldes.tutorial;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpURLPostQueryParamsExample {
public static void main(String[] args) {
String URLAddress = "http://localhost:8080/RestfulFormParamExample/rest/books/add";
String inputString = null;
int responseCode = 0;
try {
URL url = new URL(URLAddress);
try {
// Get an HttpURLConnection subclass object instead of URLConnection
HttpURLConnection myHttpConnection = (HttpURLConnection) url.openConnection();
// ensure you use the GET method
myHttpConnection.setRequestMethod("POST");
myHttpConnection.setDoOutput(true);
// create the query params
StringBuffer queryParam = new StringBuffer();
queryParam.append("isbn=");
queryParam.append("123456765");
queryParam.append("&");
queryParam.append("name=");
queryParam.append("RESTful Web Services Made Easy");
queryParam.append("&");
queryParam.append("author=");
queryParam.append("Amaury Valdes");
queryParam.append("&");
queryParam.append("publisher=");
queryParam.append("Packt");
// Output the results
OutputStream output = myHttpConnection.getOutputStream();
output.write(queryParam.toString().getBytes());
output.flush();
// get the response-code from the response
responseCode = myHttpConnection.getResponseCode();
// print out URL details
System.out.format("Connecting to %s\nConnection Method: '%s'\nResponse Code is: %d\n", URLAddress, "POST", responseCode);
System.out.println("----[ URL DETAILS ]-----------------");
System.out.println("URL Protocol....: " + url.getProtocol());
System.out.println("URL Host........: " + url.getHost());
System.out.println("URL Port........: " + url.getPort());
System.out.println("URL Authority...: " + url.getAuthority());
System.out.println("URL Path........: " + url.getPath());
System.out.println("URL User Info...: " + url.getUserInfo());
System.out.println("URL Query Info..: " + url.getQuery());
System.out.println("----[ OUTPUT BELOW ]-----------------------------------------------------------------");
// open the contents of the URL as an inputStream and print to stdout
BufferedReader in = new BufferedReader(new InputStreamReader(
myHttpConnection.getInputStream()));
while ((inputString = in.readLine()) != null) {
System.out.println(inputString);
}
in.close();
System.out.println("-------------------------------------------------------------------------------------");
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
Output of RESTful Web Service using POST
Connecting to http://localhost:8080/RestfulFormParamExample/rest/books/add Connection Method: 'POST' Response Code is: 200 ----[ URL DETAILS ]----------------- URL Protocol....: http URL Host........: localhost URL Port........: 8080 URL Authority...: localhost:8080 URL Path........: /RestfulFormParamExample/rest/books/add URL User Info...: null URL Query Info..: null ----[ OUTPUT BELOW ]----------------------------------------------------------------- addBook: Book [ISBN=123456765, name=RESTful Web Services Made Easy, author=Amaury Valdes, publisher=Packt, stockQty=0, price=0.0] -------------------------------------------------------------------------------------
RESTful Web services details
I am using the following RESTful web service in my call to to POST form data. For more details on the restful web service itself, please refer to RESTful Web Services @FormParam Example using JAX-RS and Jersey for complete details.
package com.avaldes;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import com.avaldes.model.Book;
@Path("/books")
public class RestfulFormParamExample {
static Logger logger = Logger.getLogger(RestfulFormParamExample.class);
static List<Book> bookList = new ArrayList<Book>();
@POST
@Path("/add")
@Produces(MediaType.TEXT_HTML)
public Response addBook(@FormParam("isbn") String ISBN,
@FormParam("name") String name,
@FormParam("author") String author,
@FormParam("publisher") String publisher,
@FormParam("stock_qty") int stockQty,
@FormParam("price") double price) {
Book b = new Book();
b.setISBN(ISBN);
b.setName(name);
b.setAuthor(author);
b.setPublisher(publisher);
b.setStockQty(stockQty);
b.setPrice(price);
bookList.add(b);
String msg = "addBook: " + b.toString();
logger.info(msg);
return Response.ok(msg).entity(msg).build();
}
@POST
@Path("/map")
@Produces(MediaType.TEXT_HTML)
public Response viewMap(MultivaluedMap<String, String> formFields) {
StringBuffer msg = new StringBuffer(" View all Form Fields:<br/><br/>");
for (String field : formFields.keySet()) {
msg.append(field);
msg.append(" : ");
msg.append(formFields.get(field));
msg.append("<br/>");
}
return Response.status(200).entity(msg.toString()).build();
}
@GET
@Path("/list")
public Response getBooks() {
String msg = "getBooks: " + bookList;
logger.info(msg);
return Response.ok(msg).entity(msg).build();
}
}
That’s It!
I hope you enjoyed this tutorial. If you found this tutorial useful please share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

Leave a Reply