Android从PHP服务器下载文件
我正在尝试从我的PHP服务器下载一个文件。以下是我的PHP代码:Android从PHP服务器下载文件,php,android,Php,Android,我正在尝试从我的PHP服务器下载一个文件。以下是我的PHP代码: $file = 'androidApps/app.apk'; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); header("Content-T
$file = 'androidApps/app.apk';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
文件名和文件大小正确。
当我使用我的浏览器(在我的电脑和手机上)时,一切都很好。文件已正确下载
当我尝试从android应用程序下载它时,它会下载一个38字节的文件。
仍然在我的android应用程序中,如果我使用文件的直接链接,它将正确下载。
以下是我的android代码:
String path ="http://myserverURLAndPhpFileUrl.php";//If I put the path of my file it will download it correctly
String PATH = Environment.getExternalStorageDirectory() + "/download/";
URL u = null;
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
System.out.println(len1);
}
fos.close();
is.close();`
我也尝试过使用DownloadManager,但我遇到了同样的问题:
String path = "http://myserverURLAndPhpFileUrl.php";
UpdateService.this.getSystemService(UpdateService.this.DOWNLOAD_SERVICE);
DownloadManager.Request dlrequest = new DownloadManager.Request(Uri.parse(path));
dlrequest.setVisibleInDownloadsUi(true);
dlrequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
dlrequest.setDestinationInExternalFilesDir(UpdateService.this, null, "app.apk");
System.out.println("FILE dir: " + getExternalFilesDir(null));
//nqueue this request e
DownloadManager downloadManager = (DownloadManager) UpdateService.this.getSystemService(UpdateService.this.DOWNLOAD_SERVICE);
long downloadID = downloadManager.enqueue(dlrequest);
downloadManager.enqueue(dlrequest);
我正在服务中使用此代码。
我已经在安卓5.0.1和安卓4.3上进行了测试
PHP版本:5.4.45-0+deb7u8
如何在不使用文件路径的情况下下载文件
谢谢我的代码很好。我只需要在我的请求中添加cookies:
dlrequest.addRequestHeader("Cookie","PHPSESSID="+session);
您使用了错误的url。其中没有主机。
final ByteArrayOutputStream bo=new ByteArrayOutputStream()代码>。拆下那条线。这让人困惑。使用php脚本的完整url。我没有在stackoverflow上写完整的url,但我在我的应用程序中使用了正确的url。你可以发布一个比现在更好的假url。你看它现在是多么混乱。