Simple HTTP Client Using Java

In my early career day I was very much curious and wanted to know how things work and is there any way I can try and see how I can implement certain functionality. This habit of mine helped me a lot down the line in my career. One of my last assignment required me to do some HTTP connection using Java . The requirement was simple, I needed to open a connection to specific url and write some data over the connection then analyze the response I get from url. Hearing this I was able to find a simple java class out of my inventory and that served the purpose just fine. Today I thought I would share the same with you and who knows it might add in some ones personal code inventory 🙂

Here we have a simple java class HTTPClient with a constructor that will take an url to which we want to open a HTTP connection and some utility functions that are used to prepare the pay load and for url.

You can see in the main method I am creating an HTTPClient object with url some local url (test.php). This file will simply check the variables that are coming its way and print it out on screen. ‘addParameter’ & ‘sendData’ are utility methods that are preparing payload and sending it to the url with help of functions like getOutputStream and getInputStream. Here is test.php for you.

When the java program is invoked it will simply open up the connection and prints out the response as-

HTTP Client POST Response

HTTP Client POST Response

You must have observed that the request was submitted using method POST. Now If you want to pass using GET then you to append all the parameters as query string parameter to the url as shown below-

HTTP Client GET Request

HTTP Client GET Request

That’s It! A simple HTTP Client, You never know when it can come handy.

Add a Comment

Your email address will not be published. Required fields are marked *