I am successfully using the HttpURLConnection to upload *.txt files. Now I have the task to change the program for uploading every filetype. I tried my program with .xls files. The files are placed on the server, but the content isn’t readable.
Like you see here:
ÃÃà ¡±á>þÿ
Œ¸äÌÌÌS
Sheet1Sheet2Sheet3Worksheets4 $€,þÿ3à …ŸòùOh«‘+’³Ù0Å“8Å’@x„äMicrosoft CorporationMicrosoft Excel@â€Ã¸(º»þÿ3à …ŸòùOh«‘+'³Ù0Ëœ8Å’@x„äMicrosoft CorporationMicrosoft Excel@â€Ã¸(º»@â€Ã¸(º»Ì�á°Ãâ\pMicrosoft Corporation
Here my code snippet:
HttpURLConnection urlConn = (HttpURLConnection) new URL(testdocumentURL).openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("X-Method-Override", "PUT");
urlConn.setRequestProperty("Content-Type", "text/xml");
urlConn.setRequestProperty("Authorization", "Basic "+ Client.getPassword());
urlConn.setUseCaches(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setFollowRedirects(false);
urlConn.setRequestProperty("Slug", "Connectiontest/test.xls");
String write = readFile(test.xls);
urlConn.setRequestProperty("Content-Length","" + write.length());
urlConn.getOutputStream().write(write.getBytes("UTF8"));
In my optinion there are 2 ways to solve this problem.
- change the output at .write(write.getBytes(“UTF8”))
- change the intput
At the moment I read the files like this:
readFile(String test){
BufferedReader reader = new BufferedReader(new FileReader(test));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
return stringBuilder.toString();
}
I tried to change the RequestProperty() in this ways:
connection.setRequestProperty("content-type", "multipart/form-data");
or
connection.setRequestProperty("content-type", "application/vnd.ms-excel");
Do somebody know to Upload a .xls file like this? I have to prefere the HttpURLConnector, my boss said. :/
Thanks a lot!
Don’t treat the Excel file as a
String. ChangereadFileto read the file into abyte[]instead, then write that to the connection output stream.