{"id":390,"date":"2014-06-28T17:22:52","date_gmt":"2014-06-28T09:22:52","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=390"},"modified":"2018-12-02T14:08:25","modified_gmt":"2018-12-02T06:08:25","slug":"how-to-send-http-post-requests-with-java-without-using-any-external-libraries","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-send-http-post-requests-with-java-without-using-any-external-libraries\/","title":{"rendered":"How to send HTTP POST request with Java without using any external libraries"},"content":{"rendered":"<p>I need to create a Java solution that will be able to send some bulk processing information back to a HTTP server endpoint. The Java solution should be as lean as possible, using as many facilities that Java provides out of the box. Luckily for me, Java do provides the <code>java.net.HttpURLConnection<\/code> class for me to build my solution. This post details a proof of concept which I did to get to know more about the <code>java.net.HttpURLConnection<\/code> class. <\/p>\n<p>In this proof of concept, I create a Java console program that will hit the php endpoint which I had created earlier to proof that I can <a href=\"https:\/\/www.techcoil.com\/blog\/how-i-used-jquery-to-push-a-dynamically-generated-file-to-the-web-browser-based-on-the-user-input\/\" title=\"How I used jQuery to push a dynamically generated file to the web browser based on the user\u2019s input\" target=\"_blank\">use jQuery to push a dynamically generated file to the web browser based on the user\u2019s input<\/a>.<\/p>\n<h3>Defining the server endpoint with the java.net.URL class<\/h3>\n<p>I first create an instance of the <code>java.net.URL<\/code> class, passing it the url of the server endpoint which will process my HTTP request.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nURL serverUrl = \r\n    new URL(&quot;https:\/\/www.techcoil.com\/process\/proof-of-concepts\/userNameAndLuckyNumberTextFileGeneration&quot;);\r\n<\/pre>\n<h3>Getting an instance of java.net.HttpURLConnection object to send a HTTP request to the server and receive a HTTP response from the server<\/h3>\n<p>After I had defined the server endpoint to send my HTTP request, I call the <code>open<\/code> method of the <code>URL<\/code> object:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nHttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();\r\n<\/pre>\n<p>I can then use the <code>HttpURLConnection<\/code> facilities via <code>urlConnection<\/code> to send the HTTP request to my server endpoint and read the HTTP response from it.<\/p>\n<h3>Preparing the HTTP request to send to the server endpoint<\/h3>\n<p>Once I have the <code>HttpURLConnection<\/code> object, I can write the following codes to construct the HTTP request to send to the server endpoint:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Indicate that we want to write to the HTTP request body\r\nurlConnection.setDoOutput(true);\r\nurlConnection.setRequestMethod(&quot;POST&quot;);\r\n\r\n\/\/ Writing the post data to the HTTP request body\r\nBufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));\r\nhttpRequestBodyWriter.write(&quot;visitorName=Johnny+Jacobs&amp;luckyNumber=1234&quot;);\r\nhttpRequestBodyWriter.close();\r\n<\/pre>\n<p>By default, the <code>HttpURLConnection<\/code> object does not allow me to write to the HTTP request body. As such, I first configure the <code>HttpURLConnection<\/code> object to allow me to write to the HTTP request body by calling <code>urlConnection.setDoOutput(true)<\/code>. I then call <code>urlConnection.setRequestMethod(\"POST\")<\/code> to indicate the request method as HTTP post.<\/p>\n<p>After I had configured the <code>HttpURLConnection<\/code> object, I layered the output stream to a <code>java.io.BufferedWriter<\/code> object. This allows me to write an encoded string to the HTTP request body. The encoded string sets \"Johnny Jacobs\" to the <code>visitorName<\/code> post variable and \"1234\" to the <code>luckyNumber<\/code> post variable.  <\/p>\n<h3>Reading from the HTTP response from the server endpoint<\/h3>\n<p>The HTTP request will be sent to the server endpoint when my code starts to read from <code>urlConnection<\/code>. To read the HTTP response from the server endpoint, I wrote the following codes: <\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Reading from the HTTP response body\r\nScanner httpResponseScanner = new Scanner(urlConnection.getInputStream());\r\nwhile(httpResponseScanner.hasNextLine()) {\r\n\tSystem.out.println(httpResponseScanner.nextLine());\r\n}\r\nhttpResponseScanner.close();\r\n<\/pre>\n<p>I layered the input stream of <code>urlConnection<\/code> to a <code>java.util.Scanner<\/code> object. This allows me to read the HTTP response body that the server sends back to me. I then use the <code>Scanner<\/code> object to read the response body and write to console, line by line.<\/p>\n<h3>A simple console application that sends a HTTP POST request to a server endpoint at Techcoil<\/h3>\n<p>The following sums up the points that are mentioned in this post:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.BufferedWriter;\r\nimport java.io.IOException;\r\nimport java.io.OutputStreamWriter;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.util.Scanner;\r\n\r\n\r\npublic class Program {\r\n\r\n    public static void main(String&#x5B;] args) throws IOException{\r\n\r\n    \/\/ Define the server endpoint to send the HTTP request to\r\n\tURL serverUrl = \r\n    new URL(&quot;https:\/\/www.techcoil.com\/process\/proof-of-concepts\/userNameAndLuckyNumberTextFileGeneration&quot;);\r\n\tHttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();\r\n\r\n\t\/\/ Indicate that we want to write to the HTTP request body\r\n\turlConnection.setDoOutput(true);\r\n\turlConnection.setRequestMethod(&quot;POST&quot;);\r\n\r\n\t\/\/ Writing the post data to the HTTP request body\r\n\tBufferedWriter httpRequestBodyWriter = \r\n            new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));\r\n\thttpRequestBodyWriter.write(&quot;visitorName=Johnny+Jacobs&amp;luckyNumber=1234&quot;);\r\n\thttpRequestBodyWriter.close();\r\n\r\n\t\/\/ Reading from the HTTP response body\r\n\tScanner httpResponseScanner = new Scanner(urlConnection.getInputStream());\r\n\twhile(httpResponseScanner.hasNextLine()) {\r\n\t\tSystem.out.println(httpResponseScanner.nextLine());\r\n\t}\r\n\thttpResponseScanner.close();\r\n\r\n    }\r\n}\r\n<\/pre>\n<p>Any instances of java.io.IOException will be shown in the console screen. With that, I concluded my proof of concept of sending a HTTP POST request to a server endpoint with the facilities that Java provides me with.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-6i\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-6i&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-6i&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F390&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>I need to create a Java solution that will be able to send some bulk processing information back to a HTTP server endpoint. The Java solution should be as lean as possible, using as many facilities that Java provides out of the box. Luckily for me, Java do provides the <code>java.net.HttpURLConnection<\/code> class for me to build my solution. This post details a proof of concept which I did to get to know more about the <code>java.net.HttpURLConnection<\/code> class. <\/p>\n<p>In this proof of concept, I create a Java console program that will hit the php endpoint which I had created earlier to proof that I can <a href=\"http:\/\/www.techcoil.com\/blog\/how-i-used-jquery-to-push-a-dynamically-generated-file-to-the-web-browser-based-on-the-user-input\/\" title=\"How I used jQuery to push a dynamically generated file to the web browser based on the user\u2019s input\" target=\"_blank\">use jQuery to push a dynamically generated file to the web browser based on the user\u2019s input<\/a>.<\/p>\n","protected":false},"author":1,"featured_media":1220,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[23,161,6],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-6i","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/390"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=390"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/390\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1220"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=390"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=390"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=390"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}