当我在浏览器中复制并粘贴以下网址时,会自动下载.bin文件。
但是,如果我尝试使用Android代码下载相同的文件,它只下载到.bin文件,但包含html代码。我使用下面的代码。 我希望.bin可以在浏览器中手动运行时下载。 请帮忙。
代码段:
public static String downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
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 = "create.bin";
}
} else {
// extracts file name from URL
fileName = "create.bin";
}
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int len1 = 0;
byte[] chunk = new byte[1024];
while ( (len1 = inputStream.read(chunk)) > 0 ) {
Log.e("Test","chunk: "+chunk);
outputStream.write(chunk,0, len1);
//mListener.notifyActionProgress(len1);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
}