title: Downloading HTML instead of File
body: <p>I'm using Java code to download a file from the Internet and save it to some directory.</p>
  
  <p>However, the code downloads the <code>HTML</code> source code of the page instead of the file contents.</p>
  
  <p>The code below illustrates the problem:</p>
  
  <pre><code>import java.awt.*;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.net.URL;
  import java.nio.channels.Channels;
  import java.nio.channels.ReadableByteChannel;
  
  public class JavaFileDownloadTest
  {
      public static void download(String remoteURL, String targetFilePath)
              throws IOException
      {
          URL downloadableFile = new URL(remoteURL);
          ReadableByteChannel readableByteChannel = Channels.newChannel(downloadableFile.openStream());
          FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath);
          fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
      }
  
      public static void main(String[] arguments) throws IOException
      {
          String userHome = System.getProperty("user.home");
          String fileName = "Test.txt";
          String targetFilePath = userHome + File.separator + "Downloads" + File.separator + fileName;
          download("http://bullywiiplaza.cuccfree.com/" + fileName, targetFilePath);
          Desktop.getDesktop().open(new File(targetFilePath));
      }
  }
  </code></pre>
  
  <p>The file located <a href="http://bullywiiplaza.cuccfree.com/Test.txt" rel="nofollow">here</a> contains the text</p>
  
  <pre><code>Hello StackOverflow!
  </code></pre>
  
  <p>However, when downloaded using the above code, I'm getting the <code>HTML</code> source code as file content instead:</p>
  
  <pre><code>&lt;html&gt;&lt;body&gt;&lt;script type="text/javascript" src="/aes.js" &gt;&lt;/script&gt;&lt;script&gt;function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&amp;&amp;arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f&lt;d.length;f++)e+=(16&gt;d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("ae71113e4baf38cee1c1aacf0ae66c00");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; document.cookie="referrer="+escape(document.referrer); location.href="http://bullywiiplaza.cuccfree.com/Test.txt?ckattempt=1";&lt;/script&gt;&lt;noscript&gt;This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support&lt;/noscript&gt;&lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>Why is this and how do I fix it? I already tried various libraries and methods for downloading files but all of them yielded this same "faulty" result.</p>