{"id":1387,"date":"2018-12-03T00:10:10","date_gmt":"2018-12-02T16:10:10","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1387"},"modified":"2018-12-03T00:13:08","modified_gmt":"2018-12-02T16:13:08","slug":"how-to-download-a-file-via-http-get-and-http-post-in-java-without-using-any-external-libraries","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-download-a-file-via-http-get-and-http-post-in-java-without-using-any-external-libraries\/","title":{"rendered":"How to download a file via HTTP GET and HTTP POST in Java without using any external libraries"},"content":{"rendered":"<p>Apart from <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-via-a-http-multipart-request-in-java-without-using-any-external-libraries\/\" rel=\"noopener\" target=\"_blank\">uploading a file to a HTTP server endpoint<\/a>, another common task for a Java <a href=\"https:\/\/www.techcoil.com\/glossary\/http-client\/\" rel=\"noopener\" target=\"_blank\">HTTP client<\/a> is to download a file from a <a href=\"http:\/\/www.techcoil.com\/glossary\/http-server\/\" rel=\"noopener\" target=\"_blank\">HTTP server<\/a>. Even though there are many Java external libraries to help us do so, using the facilities in the Java standard runtime installation is not difficult. Furthermore, we will be able to keep our Java application leaner if we can download files without additional dependencies.<\/p>\n<p>In case you need a reference, this is how to download a file via HTTP GET and HTTP POST in Java without using any external libraries.<\/p>\n<h2>Downloading a file from a HTTP server endpoint via HTTP GET<\/h2>\n<p>Generally, downloading a file from a HTTP server endpoint via HTTP GET consists of the following steps:<\/p>\n<ul>\n<li>Construct the HTTP GET request to send to the HTTP server.<\/li>\n<li>Send the <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP request<\/a> and receive the <a href=\"https:\/\/www.techcoil.com\/glossary\/http-response\/\" rel=\"noopener\" target=\"_blank\">HTTP Response<\/a> from the HTTP server.<\/li>\n<li>Save the contents of the file from HTTP Response to a local file.<\/li>\n<\/ul>\n<h3>Java codes to download a file from a HTTP server endpoint via HTTP GET<\/h3>\n<p>Given these points, let us modify the codes from <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-send-http-get-request-with-java-without-using-any-external-libraries\/\" rel=\"noopener\" target=\"_blank\">how to send a HTTP GET request in Java<\/a> to save the contents of the file from a HTTP Response to a local file:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.IOException;\r\nimport java.io.FileOutputStream;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.nio.channels.Channels;\r\nimport java.nio.channels.FileChannel;\r\nimport java.nio.channels.ReadableByteChannel;\r\n\r\npublic class HttpGetDownloadFileExample {\r\n\r\n    public static void main(String&#x5B;] args) {\r\n\r\n        ReadableByteChannel readableChannelForHttpResponseBody = null;\r\n        FileChannel fileChannelForDownloadedFile = null;\r\n\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            \/\/ Get a readable channel from url connection\r\n            readableChannelForHttpResponseBody = Channels.newChannel(urlConnection.getInputStream());\r\n\r\n            \/\/ Create the file channel to save file\r\n            FileOutputStream fosForDownloadedFile = new FileOutputStream(&quot;robots.txt&quot;);\r\n            fileChannelForDownloadedFile = fosForDownloadedFile.getChannel();\r\n\r\n            \/\/ Save the body of the HTTP response to local file\r\n            fileChannelForDownloadedFile.transferFrom(readableChannelForHttpResponseBody, 0, Long.MAX_VALUE);\r\n\r\n        } catch (IOException ioException) {\r\n            System.out.println(&quot;IOException occurred while contacting server.&quot;);\r\n        } finally {\r\n\r\n            if (readableChannelForHttpResponseBody != null) {\r\n\r\n                try {\r\n                    readableChannelForHttpResponseBody.close();\r\n                } catch (IOException ioe) {\r\n                    System.out.println(&quot;Error while closing response body channel&quot;);\r\n                }\r\n            }\r\n\r\n            if (fileChannelForDownloadedFile != null) {\r\n\r\n                try {\r\n                    fileChannelForDownloadedFile.close();\r\n                } catch (IOException ioe) {\r\n                    System.out.println(&quot;Error while closing file channel for downloaded file&quot;);\r\n                }\r\n            }\r\n\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>As shown above, we had created a class with a main method. When the main method is executed, our Java program does several things.<\/p>\n<p>Firstly, we had declared an instance of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/nio\/channels\/ReadableByteChannel.html\" rel=\"noopener\" target=\"_blank\"><code>ReadableByteChannel<\/code><\/a> and an instance of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/nio\/channels\/FileChannel.html\" rel=\"noopener\" target=\"_blank\"><code>FileChannel<\/code><\/a> to contain null values so as to facilitate closure in the <code>finally<\/code> block.<\/p>\n<p>After we had done so, we define a <code>try<\/code> block for running the file download logic that may throw checked <a href=\"https:\/\/www.techcoil.com\/blog\/some-information-about-exceptions-in-software-systems\/\" rel=\"noopener\" target=\"_blank\">exceptions<\/a>.<\/p>\n<p>Within the <code>try<\/code> block, we first use an instance of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/net\/URL.html\" rel=\"noopener\" target=\"_blank\">URL<\/a> to get an instance of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/net\/HttpURLConnection.html\" rel=\"noopener\" target=\"_blank\"><code>HttpURLConnection<\/code><\/a> that points to a HTTP server endpoint for the file that we wish to download.<\/p>\n<p>Once we have done so, we get an instance of <code>ReadableByteChannel<\/code> that is mapped to the input stream of <code>urlConnection<\/code>. In addition, we set it to the <code>readableChannelForHttpResponseBody<\/code> variable for manipulation later.<\/p>\n<p>After we had an instance of <code>ReadableByteChannel<\/code>, we then proceed to get a FileChannel that will point to a local file path where we want to save the downloaded file. In this case, we want to save the downloaded file as <code>robots.txt<\/code> in the same directory where we run our Java program. <\/p>\n<p>Finally, we use <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/nio\/channels\/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel,%20long,%20long)\" rel=\"noopener\" target=\"_blank\"><code>fileChannelForDownloadedFile.transferFrom<\/code><\/a> method on <code>readableChannelForHttpResponseBody<\/code> to save the contents of the HTTP response body to the local file.<\/p>\n<h2>Downloading a file from a HTTP server endpoint via HTTP POST<\/h2>\n<p>There can be cases where the client need to supply some information to the HTTP server in order to download a file. In such a situation, HTTP POST is a more appropriate HTTP method to use for downloading the file.<\/p>\n<p>As with HTTP GET, downloading of a file from the HTTP server via HTTP POST consists of the following steps:<\/p>\n<ul>\n<li>Construct the HTTP POST request to send to the HTTP server.<\/li>\n<li>Send the HTTP request and receive the HTTP Response from the HTTP server.<\/li>\n<li>Save the contents of the file from HTTP Response to a local file.<\/li>\n<\/ul>\n<h3>Java codes to download a file from a HTTP server endpoint via HTTP POST<\/h3>\n<p>Given these points, let's modify the Java code from <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-send-http-post-requests-with-java-without-using-any-external-libraries\/\" rel=\"noopener\" target=\"_blank\">how to send a HTTP POST request in Java<\/a> to save the contents of the file from a HTTP Response to a local file:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.BufferedWriter;\r\nimport java.io.IOException;\r\nimport java.io.FileOutputStream;\r\nimport java.io.OutputStreamWriter;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.nio.channels.Channels;\r\nimport java.nio.channels.FileChannel;\r\nimport java.nio.channels.ReadableByteChannel;\r\n\r\npublic class HTTPPostDownloadFileExample {\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        URL serverUrl =\r\n                new URL(&quot;https:\/\/www.techcoil.com\/process\/proof-of-concepts\/userNameAndLuckyNumberTextFileGeneration&quot;);\r\n        HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();\r\n\r\n        \/\/ Indicate that we want to write to the HTTP request body\r\n        urlConnection.setDoOutput(true);\r\n        urlConnection.setRequestMethod(&quot;POST&quot;);\r\n\r\n        \/\/ Writing the post data to the HTTP request body\r\n        BufferedWriter httpRequestBodyWriter =\r\n                new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));\r\n        httpRequestBodyWriter.write(&quot;visitorName=Johnny+Jacobs&amp;luckyNumber=1234&quot;);\r\n        httpRequestBodyWriter.close();\r\n\r\n        \/\/ Get a readable channel from url connection\r\n        ReadableByteChannel readableChannelForHttpResponseBody = Channels.newChannel(urlConnection.getInputStream());\r\n\r\n        \/\/ Create the file channel to save file\r\n        FileOutputStream fosForDownloadedFile = new FileOutputStream(&quot;luckyNumber.txt&quot;);\r\n        FileChannel fileChannelForDownloadedFile = fosForDownloadedFile.getChannel();\r\n\r\n        \/\/ Save the contents of HTTP response to local file\r\n        fileChannelForDownloadedFile.transferFrom(readableChannelForHttpResponseBody, 0, Long.MAX_VALUE);\r\n    }\r\n}\r\n<\/pre>\n<p>As shown above, we had created a class with a main method which will propagate any occurrences of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/io\/IOException.html\" rel=\"noopener\" target=\"_blank\">IOException<\/a> back to the caller. When the main method is executed, our Java program does several things. <\/p>\n<p>First, it creates an instance of <code>HttpURLConnection<\/code>, <code>urlConnection<\/code>, that maps to the HTTP server endpoint at <code>https:\/\/www.techcoil.com\/process\/proof-of-concepts\/userNameAndLuckyNumberTextFileGeneration<\/code>. Given that, we then configure <code>urlConnection<\/code> to allow us to write to the HTTP request body via <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/net\/URLConnection.html#setDoOutput(boolean)\" rel=\"noopener\" target=\"_blank\">urlConnection.setDoOutput(true)<\/a>. After that, we set the HTTP method of the HTTP request as POST via <code>urlConnection.setRequestMethod(\"POST\")<\/code>.<\/p>\n<p>Next, we use an instance of <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/io\/BufferedWriter.html\" rel=\"noopener\" target=\"_blank\">BufferedWriter<\/a> to write some POST variables to the HTTP request body. <\/p>\n<p>Once we had written the POST variables, we then get an instance of <code>ReadableByteChannel<\/code> from the input stream of <code>urlConnection<\/code>. Given that instance, we will then be able to read from the body of the HTTP response.<\/p>\n<p>After we had an instance of <code>ReadableByteChannel<\/code>, we then proceed to get an instance of <code>FileChannel<\/code> that will point to a local file path where we want to save the downloaded file. In this case, we will save the downloaded file as <code>luckyNumber.txt<\/code> in the same directory where we run our Java program. <\/p>\n<p>Finally, we use <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/nio\/channels\/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel,%20long,%20long)\" rel=\"noopener\" target=\"_blank\"><code>fileChannelForDownloadedFile.transferFrom<\/code><\/a> on <code>readableChannelForHttpResponseBody<\/code> to save the contents of the HTTP response body to the local file.<\/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-mn\" 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-mn&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-mn&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%2F1387&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>Apart from <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-via-a-http-multipart-request-in-java-without-using-any-external-libraries\/\" rel=\"noopener\" target=\"_blank\">uploading a file to a HTTP server endpoint<\/a>, another common task for a Java <a href=\"https:\/\/www.techcoil.com\/glossary\/http-client\/\" rel=\"noopener\" target=\"_blank\">HTTP client<\/a> is to download a file from a <a href=\"http:\/\/www.techcoil.com\/glossary\/http-server\/\" rel=\"noopener\" target=\"_blank\">HTTP server<\/a>. Even though there are many Java external libraries to help us do so, using the facilities in the Java standard runtime installation is not difficult. Furthermore, we will be able to keep our Java application leaner if we can download files without additional dependencies.<\/p>\n<p>In case you need a reference, this is how to download a file via HTTP GET and HTTP POST in Java without using any external libraries.<\/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":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[23,199,161,6,591,592,462,470,595,593,594],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-mn","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1387"}],"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=1387"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1387\/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=1387"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1387"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1387"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}