【发布时间】:2016-03-13 09:51:51
【问题描述】:
如何使用 Retrofit2 从我的 PHP 服务器下载 文件(图像/视频)?
我无法在网上找到任何有关如何进行操作的资源或教程;我发现this post 处理 SO 上的某个下载错误,但我不太清楚。谁能指出我正确的方向?
更新:
这是我的代码:
FileDownloadService.java
public interface FileDownloadService {
@GET(Constants.UPLOADS_DIRECTORY + "/{filename}")
@Streaming
Call<ResponseBody> downloadRetrofit(@Path("filename") String fileName);
}
MainActivity.java(@Blackbelt的解决方案)
private void downloadFile(String filename) {
FileDownloadService service = ServiceGenerator
.createService(FileDownloadService.class, Constants.SERVER_IP_ADDRESS);
Call<ResponseBody> call = service.downloadRetrofit("db90408a4bb1ee65d3e09d261494a49f.jpg");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(final Response<ResponseBody> response, Retrofit retrofit) {
try {
InputStream is = response.body().byteStream();
FileOutputStream fos = new FileOutputStream(
new File(Environment.getExternalStorageDirectory(), "image.jpg")
);
int read = 0;
byte[] buffer = new byte[32768];
while ((read = is.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.close();
is.close();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Failed to download file...", Toast.LENGTH_LONG).show();
}
});
}
当 USB 调试处于活动状态时,我得到一个 FileNotFoundException,而当没有启用时,我得到一个 NetworkOnMainThreadException。
MainActivity.java:(@Emanuel的解决方案)
private void downloadFile(String filename) {
FileDownloadService service = ServiceGenerator
.createService(FileDownloadService.class, Constants.SERVER_IP_ADDRESS);
Call<ResponseBody> call = service.downloadRetrofit("db90408a4bb1ee65d3e09d261494a49f.jpg");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(final Response<ResponseBody> response, Retrofit retrofit) {
Log.i(TAG, "external storage = " + (Environment.getExternalStorageState() == null));
Toast.makeText(MainActivity.this, "Downloading file... " + Environment.getExternalStorageDirectory(), Toast.LENGTH_LONG).show();
File file = new File(Environment.getDataDirectory().toString() + "/aouf/image.jpg");
try {
file.createNewFile();
Files.asByteSink(file).write(response.body().bytes());
} catch (Exception e) {
Toast.makeText(MainActivity.this,
"Exception: " + e.toString(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Failed to download file...", Toast.LENGTH_LONG).show();
}
});
}
我收到 FileNotFoundException。
【问题讨论】:
-
尝试找出产生
NetworkOnMainThreadException的行调用并从另一个线程调用它。或者从另一个线程调用整个downloadFile(...)方法:new Thread(new Runnable() { public void run() { downloadFile("filename"); } }).start();
标签: java php android download retrofit