{"id":421,"date":"2015-02-08T16:44:04","date_gmt":"2015-02-08T08:44:04","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=421"},"modified":"2018-09-22T15:56:58","modified_gmt":"2018-09-22T07:56:58","slug":"how-to-upload-a-file-via-a-http-multipart-request-in-java-without-using-any-external-libraries","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-upload-a-file-via-a-http-multipart-request-in-java-without-using-any-external-libraries\/","title":{"rendered":"How to upload a file via a HTTP multipart request in Java without using any external libraries"},"content":{"rendered":"<p>There was this situation when there was a need for my applet to send some log files (generated by some desktop application) on the remote clients.<\/p>\n<p>To keep my applet lean, I chose to implement this file upload function by sending a <a href=\"https:\/\/www.techcoil.com\/glossary\/http\/\" rel=\"noopener\" target=\"_blank\">HTTP<\/a> multipart request when my applet loads on the remote client's browser. Policies were in place to ensure that my applet was able to read the log files and send them back to a web server which will collect the log files.<\/p>\n<p>This post documents how I can upload a file by sending a HTTP multipart request in Java without using any external libraries. For the sake of brevity, I used the <a title=\"How to receive HTTP post data and a file from a C# program using PHP\" href=\"http:\/\/www.techcoil.com\/blog\/how-to-receive-http-post-data-and-a-file-from-a-c-program-using-php\/\" target=\"_blank\">server endpoint that I had discussed earlier<\/a> to accept the file from the codes that will be mentioned in this post.<\/p>\n<h2>Having an idea of what the HTTP multipart request will look like<\/h2>\n<p>One way to know how a HTTP multipart request will look like will be to capture the HTTP multipart request that browsers send web servers. To instruct my browser to show me how my Java program should send the HTTP multipart request, I first create the following HTML code:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;body&gt;\r\n&lt;form action=&quot;http:\/\/ipv4.fiddler\/test\/GetPostRequest.php&quot;\r\nmethod=&quot;post&quot;\r\nenctype=&quot;multipart\/form-data&quot;&gt;\r\n&lt;p&gt;\r\n&lt;strong&gt;My file description:&lt;\/strong&gt;\r\n&lt;textarea name=&quot;myFileDescription&quot; rows=&quot;2&quot; cols=&quot;20&quot;&gt;\r\n&lt;\/textarea&gt;&lt;br\/&gt; &lt;br\/&gt;\r\n&lt;strong&gt;My file:&lt;\/strong&gt;&lt;br\/&gt;\r\n&lt;input type=&quot;file&quot; name=&quot;myFile&quot;&gt;\r\n&lt;\/p&gt;\r\n&lt;input type=&quot;submit&quot; value = &quot;Submit&quot;&gt;\r\n&lt;\/form&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>And then point my browser to the HTML file. I then use the HTML form to upload a file and have <a title=\"Home page for Fiddle 2\" href=\"http:\/\/www.fiddler2.com\/fiddler2\/\" target=\"_blank\">Fiddler<\/a> examine the HTTP multipart request.<\/p>\n<p>Fiddler showed me the following:<\/p>\n<pre><code>POST http:\/\/127.0.0.1\/GetPostRequest.php \r\nHTTP\/1.1 Host: 127.0.0.1 \r\nConnection: keep-alive \r\nReferer: http:\/\/localhost\/GetPostRequest.php \r\nContent-Length: 864 \r\nCache-Control: max-age=0 \r\nOrigin: http:\/\/localhost \r\nUser-Agent: Mozilla\/5.0 (Windows NT 6.1; WOW64) AppleWebKit\/534.30 (KHTML, like Gecko) Chrome\/12.0.742.91 Safari\/534.30 \r\nContent-Type: multipart\/form-data; boundary=----WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nAccept: text\/html,application\/xhtml+xml,application\/xml;q=0.9,*\/*;q=0.8 \r\nAccept-Encoding: gzip,deflate,sdch \r\nAccept-Language: en-US,en;q=0.8 \r\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n\r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nContent-Disposition: form-data; name=\"myFileDescription\" \r\n\r\nLog file for 20150208. \r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb \r\nContent-Disposition: form-data; name=\"myFile\"; filename=\"20150208.log\" \r\nContent-Type: text\/plain\r\n\r\nfile contents... \r\n\r\n------WebKitFormBoundaryX6nBO7q27yQ1JNbb--<\/code><\/pre>\n<h2>Constructing a HTTP multipart request to upload the file to the web server endpoint<\/h2>\n<p>With the output from Fiddler, sending the HTTP multipart request with my Java program is straightforward. To avoid using external libraries, I use the following classes provided by the Java standard library:<\/p>\n<ul>\n<li>java.io.BufferedReader<\/li>\n<li>java.io.BufferedWriter<\/li>\n<li>java.io.File<\/li>\n<li>java.io.FileInputStream<\/li>\n<li>java.io.InputStreamReader<\/li>\n<li>java.io.OutputStream<\/li>\n<li>java.io.OutputStreamWriter<\/li>\n<li>java.net.HttpURLConnection<\/li>\n<li>java.net.URL<\/li>\n<\/ul>\n<p>And wrote the following codes to upload my log file to my web server endpoint with a HTTP multipart request.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Connect to the web server endpoint\r\nURL serverUrl =\r\n    new URL(&quot;http:\/\/localhost\/test\/GetPostRequest.php&quot;);\r\nHttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();\r\n\r\nString boundaryString = &quot;----SomeRandomText&quot;;\r\nString fileUrl = &quot;\/logs\/20150208.log&quot;;\r\nFile logFileToUpload = new File(fileUrl);\r\n\r\n\/\/ Indicate that we want to write to the HTTP request body\r\nurlConnection.setDoOutput(true);\r\nurlConnection.setRequestMethod(&quot;POST&quot;);\r\nurlConnection.addRequestProperty(&quot;Content-Type&quot;, &quot;multipart\/form-data; boundary=&quot; + boundaryString);\r\n\r\nOutputStream outputStreamToRequestBody = urlConnection.getOutputStream();\r\nBufferedWriter httpRequestBodyWriter =\r\n    new BufferedWriter(new OutputStreamWriter(outputStreamToRequestBody));\r\n\r\n\/\/ Include value from the myFileDescription text area in the post data\r\nhttpRequestBodyWriter.write(&quot;\\n\\n--&quot; + boundaryString + &quot;\\n&quot;);\r\nhttpRequestBodyWriter.write(&quot;Content-Disposition: form-data; name=\\&quot;myFileDescription\\&quot;&quot;);\r\nhttpRequestBodyWriter.write(&quot;\\n\\n&quot;);\r\nhttpRequestBodyWriter.write(&quot;Log file for 20150208&quot;);\r\n\r\n\/\/ Include the section to describe the file\r\nhttpRequestBodyWriter.write(&quot;\\n--&quot; + boundaryString + &quot;\\n&quot;);\r\nhttpRequestBodyWriter.write(&quot;Content-Disposition: form-data;&quot;\r\n        + &quot;name=\\&quot;myFile\\&quot;;&quot;\r\n        + &quot;filename=\\&quot;&quot;+ logFileToUpload.getName() +&quot;\\&quot;&quot;\r\n        + &quot;\\nContent-Type: text\/plain\\n\\n&quot;);\r\nhttpRequestBodyWriter.flush();\r\n\r\n\/\/ Write the actual file contents\r\nFileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);\r\n\r\nint bytesRead;\r\nbyte&#x5B;] dataBuffer = new byte&#x5B;1024];\r\nwhile((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {\r\n    outputStreamToRequestBody.write(dataBuffer, 0, bytesRead);\r\n}\r\n\r\noutputStreamToRequestBody.flush();\r\n\r\n\/\/ Mark the end of the multipart http request\r\nhttpRequestBodyWriter.write(&quot;\\n--&quot; + boundaryString + &quot;--\\n&quot;);\r\nhttpRequestBodyWriter.flush();\r\n\r\n\/\/ Close the streams\r\noutputStreamToRequestBody.close();\r\nhttpRequestBodyWriter.close();\r\n<\/pre>\n<h2>Getting the HTTP response from the web server<\/h2>\n<p>After writing the payload for the HTTP multipart request to the output stream of the <code>HttpURLConnection<\/code> object, I would then read the response from my web server endpoint.<\/p>\n<p>By using the <code>HttpURLConnection<\/code> object to read the HTTP response, I also trigger the actual uploading of the log file via a HTTP multipart request to the web server.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Read response from web server, which will trigger the multipart HTTP request to be sent.\r\nBufferedReader httpResponseReader =\r\n    new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\r\nString lineRead;\r\nwhile((lineRead = httpResponseReader.readLine()) != null) {\r\n    System.out.println(lineRead);\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-6N\" 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-6N&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-6N&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%2F421&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 situation when there was a need for my applet to send some log files (generated by some desktop application) on the remote clients.<\/p>\n<p>To keep my applet lean, I chose to implement this file upload function by sending a <a href=\"https:\/\/www.techcoil.com\/glossary\/http\/\" rel=\"noopener\" target=\"_blank\">HTTP<\/a> multipart request when my applet loads on the remote client&#8217;s browser. Policies were in place to ensure that my applet was able to read the log files and send them back to a web server which will collect the log files.<\/p>\n<p>This post documents how I can upload a file by sending a HTTP multipart request in Java without using any external libraries. For the sake of brevity, I used the <a title=\"How to receive HTTP post data and a file from a C# program using PHP\" href=\"http:\/\/www.techcoil.com\/blog\/how-to-receive-http-post-data-and-a-file-from-a-c-program-using-php\/\" target=\"_blank\">server endpoint that I had discussed earlier<\/a> to accept the file from the codes that will be mentioned in this post.<\/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":[166,23,137,6,463,464,465,466,467,468,469,462,470],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-6N","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/421"}],"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=421"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/421\/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=421"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=421"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=421"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}