0

First of all, sorry for my bad english, is not my first language. I'm coding a method that downloads a file from internet. I know there are several ways to do that, but my issue is still happening , no matter what method I use.

The code should download a .torrent file, and it does, but the "final" file seems to be corrupted. Let me guide you through the following pictures:

a common torrent file downloaded from the web (using a navigator) at least is in english

the same torrent file, but downloaded from my java code wtf

The download process goes wrong, as far as I concern. I tried the following two ways and both of them download the same "encoded" thing.

Possible solution #1 - java.nio

  //Get .torrent file
public void getTorrentFile(String torrentURL, String fileName) {
   try {
    URL website = new URL(torrentURL);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(fileName);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        } catch (MalformedURLException mue) { mue.printStackTrace(); }
        catch (IOException ioe) {
            ioe.printStackTrace(); }

        }
}

*Possible solution #2 - The loop *

    File torrentFile = new File(fileName);
    URLConnection conn = new URL(torrentURL).openConnection();

        conn.connect();

    try (InputStream in = conn.getInputStream(); OutputStream out = new                 FileOutputStream(torrentFile)) {
        int b = 0;
        while (b != -1) {
            b = in.read();
            if (b != -1) {
                out.write(b);

            }
        }
    } catch (IOException ioe) { ioe.printStackTrace(); }
    } catch (IOException ioe) { ioe.printStackTrace(); }

As I said before, this 2 solutions are wrong. They are useful to download a file, but some of the torrents that I want to download, come corrupt.

Why does my file comes "corrupt" to my pc? Thanks in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

0

You need to check the response headers; specifically the "content-type", "content-encoding" and "transfer-encoding". After the conn.connect() call, add a call to getHeaderFields() and print out the contents of the map.

Depending on what you see there, you may need to add request headers to tell the server to encode the response body differently.

Refer to the HTTP 1.1 Specification for a description of what the various response headers mean. Also read about the "accept-*" headers that you can set in the request.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216