【发布时间】:2013-11-30 17:10:27
【问题描述】:
我可以从网站下载文件。当我通过 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();
【问题讨论】:
-
你能给出正在使用的两个请求吗?一个有效,另一个无效?它们之间的区别可以解释为什么一个有效而另一个无效
-
当我通过 java main 方法调用相同的方法时,它可以工作......当我将相同的代码与我的 spring mvc 集成,并部署在 tomcat 中时,它不会......我得到的响应是...内容类型=文本/html; charset=utf-8 .... 这是错误的。它应该是 Content-Type =application/vnd.openxmlformats-officedocument.wordprocessingml.document
-
text/html响应可能是从 Tomcat/Spring 发送时从服务器返回的错误页面(可能是 404)。您能否确认您使用的fileURL在这两种情况下都完全相同?也许您可以添加System.out.println("fileURL");,然后重新运行这两个测试。
标签: spring-mvc httpurlconnection