我真的坚持这个问题并希望得到一些帮助。我自动登录到服务器并下载Excel(xlsx)文件。下载似乎工作正常,因为大小与服务器上的相同,如果我用XML-Editor打开文件,它看起来有效(与其他excel文件相比)。 但是如果我尝试用excel打开下载的文件,我得到了一个"该文件可能已损坏"消息,它不可读。
我尝试更改文件的编码,即GET-Request的标头,甚至尝试将其编写为Bytestream。没有改变。
以下是一些相关的代码段:
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;
}
下载课程
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());
}
您可以在某些注释行中看到我的尝试。
我感谢任何帮助。提前谢谢。