我可以从网站下载文件。当我通过java main方法运行它时,文件被下载并且响应是
Content-Type =application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Disposition = attachment;
filename = test.docx
Content-Length = -1
fileName = test.doc
File downloaded
但是当我将它集成到我的spring mvc应用程序中时,它并没有...我得到了响应,
Content-Type =text/html; charset=utf-8
content-disposition=null
content-length=-1
该文件未下载... 请帮我解决这个问题。 提前致谢
//code
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Cookie", "cookie-name");
//add request header
httpConn.setRequestProperty("User-Agent", "test");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null)
{
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
}
else
{
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = "E:/" + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
}
else
{
System.out.println("No file to download"):
}
httpConn.disconnect();
答案 0 :(得分:0)
我明白了。似乎我在调用下载文件的URL中存在问题。 url本身返回了打印响应,而不是下载响应,这就是它无法正常工作的原因。
错误来自我的结局......
感谢所有试图帮助我的人。