{"id":392,"date":"2014-06-29T12:06:07","date_gmt":"2014-06-29T04:06:07","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=392"},"modified":"2018-09-04T13:26:28","modified_gmt":"2018-09-04T05:26:28","slug":"how-to-send-http-get-request-with-java-without-using-any-external-libraries","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-send-http-get-request-with-java-without-using-any-external-libraries\/","title":{"rendered":"How to send HTTP GET request with Java without using any external libraries"},"content":{"rendered":"<p>There was this time when I need to build a program to check whether my web server is running fine. To determine that my web server is running fine, I wrote a Java applet that sends a HTTP GET to one of my web resources when the applet runs for the first time. And to keep the applet light, I look into Java in-built features for sending HTTP GETs to my server. This post documents a proof of concept that I did to communicate with my server endpoint via HTTP GET using Java in-built features.<\/p>\n<h3>Defining the server endpoint to connect to<\/h3>\n<p>I chose to use my <code>robots.txt<\/code> for probing whether my server is running fine. To probe my server, I write the following codes:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nURL robotsUrl = new URL(&quot;http:\/\/www.techcoil.com\/robots.txt&quot;);\r\nHttpURLConnection urlConnection = (HttpURLConnection) robotsUrl.openConnection();  \r\n<\/pre>\n<p>I first create a <code>java.net.URL<\/code> object to my <code>robots.txt<\/code>. I then call <code>robotsUrl.openConnection()<\/code> to get a <code>java.net.HttpURLConnection<\/code> object that will allow me to send a HTTP request to my server to get <code>robots.txt<\/code> as a HTTP response.<\/p>\n<h3>Configuring the HttpURLConnection<\/h3>\n<p>Unlike <a href=\"http:\/\/www.techcoil.com\/blog\/how-to-send-http-post-requests-with-java-without-using-any-external-libraries\/\" title=\"How to send HTTP POST request with Java without using any external libraries\" target=\"_blank\">sending a HTTP POST to the server endpoint<\/a>, no additional configurations is needed for the <code>HttpURLConnection<\/code> object as the default request method is set to HTTP GET and we do not need to write anything as the HTTP request body.<\/p>\n<h3>Sending the HTTP request and verifying the HTTP response<\/h3>\n<p>The HTTP request will be sent to the server when we read from our <code>HttpURLConnection<\/code> object. As such, the next step will be to read the HTTP response body from <code>urlConnection<\/code> and verify the contents. The contents should contain the string \"Sitemap: http:\/\/www.techcoil.com\/sitemap-index.xml\". <\/p>\n<p>To do so, I wrote the following codes:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nScanner httpResponseBodyScanner = new Scanner(urlConnection.getInputStream());\r\n\r\n\/\/ Use a ByteArrayOutputStream to store the contents of the HTTP response body\r\nByteArrayOutputStream responseBodyBaos = new ByteArrayOutputStream();\r\nwhile(httpResponseBodyScanner.hasNextLine()) {\r\n\tresponseBodyBaos.write(httpResponseBodyScanner.nextLine().getBytes());\r\n}\r\nresponseBodyBaos.close();\r\nhttpResponseBodyScanner.close();\r\n\r\n\/\/ Verify contents of robots.txt\r\nString robotsContent = responseBodyBaos.toString();\r\nif (robotsContent.trim().equals(&quot;Sitemap: http:\/\/www.techcoil.com\/sitemap-index.xml&quot;)) {\r\n\tSystem.out.println(&quot;Able to retrieve robots.txt from server. Server is running fine.&quot;);\r\n}\r\nelse {\r\n\tSystem.out.println(&quot;Not able to retrive robots.txt from server.&quot;);\r\n}\r\n<\/pre>\n<p>I first layered a <code>java.util.Scanner<\/code> object to the input stream of <code>urlConnection<\/code> to allow my codes to read the HTTP response body that my server sends back to me. I then use a <code>java.io.ByteArrayOutputStream<\/code> object to record the contents of the HTTP response body. <\/p>\n<p>After all the contents of my HTTP response body is recorded in the <code>java.io.ByteArrayOutputStream<\/code> object, I proceed to verify the contents, trimming any leading or trailing white spaces. If the trimmed contents is the string \"Sitemap: http:\/\/www.techcoil.com\/sitemap-index.xml\", I output \"Able to retrieve robots.txt from server. Server is running fine.\" to console. If not, I output \"Not able to retrive robots.txt from server.\" to console.<\/p>\n<h3>A simple console application that sends a HTTP GET request to a server endpoint at Techcoil to check whether Techcoil is running fine<\/h3>\n<p>To sum up the points covered in this post, I put together the following class which can be used to build a console application that checks the content of http:\/\/www.techcoil.com\/robots.txt to determine whether Techcoil is running fine:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.BufferedWriter;\r\nimport java.io.ByteArrayOutputStream;\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\npublic class Program {\r\n\r\n\tpublic static void main(String&#x5B;] args) {\r\n\t\t\r\n\t\tByteArrayOutputStream responseBodyBaos = null;\r\n        Scanner httpResponseBodyScanner = null;\r\n        try {\r\n            \/\/ Define server endpoint\r\n            URL robotsUrl = new URL(&quot;http:\/\/www.techcoil.com\/robots.txt&quot;);\r\n            HttpURLConnection urlConnection = (HttpURLConnection) robotsUrl.openConnection(); \r\n \r\n            httpResponseBodyScanner = new Scanner(urlConnection.getInputStream());\r\n \r\n            \/\/ Use a ByteArrayOutputStream to store the contents of the HTTP response body\r\n            responseBodyBaos = new ByteArrayOutputStream();\r\n            while(httpResponseBodyScanner.hasNextLine()) {\r\n                responseBodyBaos.write(httpResponseBodyScanner.nextLine().getBytes());\r\n            }\r\n            responseBodyBaos.close();\r\n            httpResponseBodyScanner.close();\r\n \r\n            \/\/ Verify contents of robots.txt\r\n            String robotsContent = responseBodyBaos.toString();\r\n            if (robotsContent.trim().equals(&quot;Sitemap: http:\/\/www.techcoil.com\/sitemap-index.xml&quot;)) {\r\n                System.out.println(&quot;Able to retrieve robots.txt from server. Server is running fine.&quot;);\r\n            }\r\n            else {\r\n                System.out.println(&quot;Not able to retrive robots.txt from server.&quot;);\r\n            }\r\n \r\n        } catch(IOException ioException) {\r\n            System.out.println(&quot;IOException occurred while contacting server.&quot;);\r\n        } finally {\r\n            if (responseBodyBaos != null) {\r\n            \ttry {\r\n                responseBodyBaos.close();\r\n            \t} catch (IOException ioe) {\r\n            \t\tSystem.out.println(&quot;Error while closing response body stream&quot;);\r\n            \t}\r\n            }\r\n            if (httpResponseBodyScanner != null) {\r\n                httpResponseBodyScanner.close();\r\n            }\r\n        }\r\n}\r\n<\/pre>\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-6k\" 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-6k&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-6k&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%2F392&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>There was this time when I need to build a program to check whether my web server is running fine. To determine that my web server is running fine, I wrote a Java applet that sends a HTTP GET to one of my web resources when the applet runs for the first time. And to keep the applet light, I look into Java in-built features for sending HTTP GETs to my server. This post documents a proof of concept that I did to communicate with my server endpoint via HTTP GET using Java in-built features.<\/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,199,137,6],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-6k","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/392"}],"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=392"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/392\/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=392"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=392"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=392"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}