我尝试从服务器下载文件并将其保存在内部存储器中,然后进行安装。 我通过这段代码使用改造下载了它
Call<ResponseBody> call = apiService.getNewVersion();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
if (response.isSuccessful() ) {
Log.d("1", "server contacted and has file");
boolean writtenToDisk =
writeResponseBodyToDisk(response.body());
Log.d("2", "file download was a success? " + writtenToDisk);
} else {
Log.d("3", "server contact failed");
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("4", "error");
}
});
我用这段代码保存了它
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new
File(context.getExternalFilesDir(null) + File.separator + "app-debug.apk");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d("TAG", "file download: " + fileSizeDownloaded + " of "
+ fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
它原来的 4.56MB 但在 Android 存储中显示为 6.08MB。 当我打开它安装它显示 version N /A size N/ A 当我尝试安装它时,它显示此 parse problem
你有解决这个问题的想法吗? 如何去除多余字节?
最佳答案
您应该确保在您的 Web 服务方法中使用 HttpResponseMessage.content
,因为正常返回将不是您想要的文件的标准大小:
[HttpGet]
[Route("api/Depository/DownloadFileFTP")] // /{pass}
public HttpResponseMessage DownloadFileFTP() //string pass
{
HttpResponseMessage result = null;
string ftphost = "*******";
string ftpfilepath = "/app-debug.apk";
byte[] fileData;
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential("**", "****");
fileData = request.DownloadData(ftpfullpath);
}
byte[] bytes = fileData;
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "app.apk";
return result;
}
关于android - 如何在不增加大小的情况下将文件另存为 apk 在 Android 中(无法安装),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44561932/