0

I am really stuck on this problem and hoping for some help. I automatically log in to a Server and download a Excel (xlsx) File. The download seems to work fine, cause the size is the same as on the server and if I open the file with an XML-Editor it looks valid (compared to other excel Files). But if I try to open the downloaded file with excel I got a "The file might be corrupt" message and it's not readable.

I tried to change the encoding of the file, the headers of the GET-Request, even tried to write it as Bytestream. Nothing changed.

Here are some relevant code snippets:

public HttpsURLConnection login()
{
    HttpsURLConnection connection = null;

    String user = "user";
    String password = "password";    

    String authString = user + ":" + password;

    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);


    try {
        connection = (HttpsURLConnection)url.openConnection();

    connection.setRequestMethod("GET");
    connection.setRequestProperty("Authorization", "Basic " + authStringEnc);  
    connection.setRequestProperty("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    //connection.setRequestProperty("Content-Type", "application/vnd.openxml");
    connection.setRequestProperty("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    //connection.setRequestProperty("Accept", "application/vnd.openxml");
    connection.setRequestProperty("User-Agent", USER_AGENT);

    connection.connect();
    } catch (IOException e) 
    {
        e.printStackTrace();
    }

    return connection;
}

The download class

private void sendGet(HttpsURLConnection con) throws Exception {


    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    String fileName = "test.xlsx";
    file = new File(fileName);
    if (!file.exists()) {
    file.createNewFile();
    }
    //use FileWriter to write file
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    //BufferedWriter bw = new BufferedWriter(fw);

    /**CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPORT);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);**/
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(fileName), "UTF-8"
        ));

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
        bw.write(inputLine);
    }
    in.close();
    bw.close();


    //print result
    //System.out.println(response.toString());

}

You can see my attempts in some of the commented lines.

I appreciate any help. Thanks in advance.

  • generate MD5 hash of file on server and the one downloaded.See if they are same. – Tomas Bisciak Apr 07 '16 at 10:34
  • "if I open the file with an XML-Editor it looks valid ": A `*.xlsx` file is **not** **one** XML file but a `ZIP` file containing multiple XML files in different folders. – Axel Richter Apr 07 '16 at 10:39
  • Thanks for the hints. The md5 is NOT identical and if I rename the excel sheet to zip, I cannot open it (other than with the original file). So it seems like the file is corrupt, but I still don't know what I do wrong :( – budadabubladend Apr 07 '16 at 11:01
  • Don't think about a `*.xlsx` file as a character stream. See it as a binary stream. Look how Java will read and write binary streams. – Axel Richter Apr 07 '16 at 11:18
  • You could probably just do `Files.copy(con.getInputStream(), Paths.get("test.xlsx"));` -- your problem is related to http://stackoverflow.com/questions/10269862/java-reading-from-a-file-input-stream-vs-reader – Teemu Ilmonen Apr 07 '16 at 11:34
  • @AxelRichter thx, but I already tried that. To make sure it doesn't change anything I did it again: `InputStreamReader in = new InputStreamReader(con.getInputStream()); byte[] bytes = IOUtils.toByteArray(in);` `FileOutputStream output = new FileOutputStream(file); IOUtils.write(bytes, output);` No change. Or am I doing something wrong? – budadabubladend Apr 07 '16 at 11:43
  • An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. – Axel Richter Apr 07 '16 at 11:46
  • Big thanks to you @AxelRichter! It was exactly as you said: If you don't use any of those Reader classes and just pass the bytestream out of the Connection to the file, you get a valid excel. Thank you! – budadabubladend Apr 07 '16 at 13:27

0 Answers0