我有一个php脚本,如果它不存在则会创建一个文件。 php脚本在创建文件后发送该文件。现在我有一个问题,我的下载类无法下载它(我不知道为什么)当php文件正在创建一个新文件。但如果php脚本发送缓存文件,则下载有效。 有没有办法让android等到php脚本执行完毕?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Looper;
import android.provider.ContactsContract.Directory;
import android.util.Log;
public class DownloadMP3 extends AsyncTask<String, Integer, String> {
private OnTaskRunning listener;
public DownloadMP3(OnTaskRunning listener){
this.listener=listener;
}
@Override
protected String doInBackground(String... url) {
int count;
try {
Log.d("Info", "create file");
Download down = new Download();
JSONObject jObject = new JSONObject(down.JSON(conf.d + "convert.php?v=" + url[0]));
Log.d("Info","json file: " + jObject.get("fle"));
URL u = new URL(conf.d + "convert.php?v=" + jObject.get("fle"));
Log.d("Info", "dl u");
URLConnection conexion = u.openConnection();
Log.d("Info", "dl op");
conexion.connect();
Log.d("Info", "dl co");
File directory = new File(Environment.getExternalStorageDirectory() + "/Music/VBT Splash/");
Log.d("Info", "dl di");
if (!directory.exists() || !directory.isDirectory()){
directory.mkdirs();
}
InputStream input = new BufferedInputStream(u.openStream());
String filename = conexion.getHeaderField("Content-Disposition");
String file = filename.substring(filename.indexOf("\"")+1, filename.lastIndexOf("\""));
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Music/VBT Splash/" + file);
int lenghtOfFile = conexion.getContentLength();
byte data[] = new byte[4096];
long total = 0;
listener.onTaskStarted();
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
publishProgress((int) (total * 100 / lenghtOfFile));
}
Log.d("Info", "dl done");
listener.onTaskDone();
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
listener.onTaskProgress(progress[0]);
}
protected void onPostExecute(int result) {
}
}
答案 0 :(得分:1)
您必须将重定向传达给您的客户端代码。如果您只是点击完整的文件路径URL,并且它不存在,则不会下载它。所以相反,首先从脚本获取下载URL。 (如果它不存在,将创建一个新的)然后,下载该URL。这使得总共有2个服务器请求。