gpt4 book ai didi

java - URLConnection 超时问题

转载 作者:行者123 更新时间:2023-11-30 00:33:09 25 4
gpt4 key购买 nike

我正在使用 android 应用程序,我正在从 url 下载文件。一切正常,但是当互联网连接介于两者之间(打开连接后)时,下载超时永远不会发生并且连接永远不会结束。

给我一​​个解决这个问题的方案

        **URL url = new URL("fileURL");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
File file = new File(context.getFilesDir(), "" + filename);
// getting file length
int lenghtOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int status = (int) ((total * 100) / lenghtOfFile);
publishProgress("" + status);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close()**

最佳答案

您可以使用 Retrofit Library 从服务器下载文件,

Retrofit 内部使用 OkHttp

请引用以下网址,

https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server

final FileDownloadService downloadService =
ServiceGenerator.createService(FileDownloadService.class);

Call<ResponseBody> call =
downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody>
response) {
if (response.isSuccessful()) {
Log.d(TAG, "server contacted and has file");

new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(FileDownloadActivity.this, response.body(), null);

Log.d(TAG, "file download was a success? " + writtenToDisk);
return null;
}
}.execute();
} else {
Log.d(TAG, "server contact failed");
}
}

而且你还可以对大文件使用@Streaming注解。 Retrofit 也将处理大文件下载

关于java - URLConnection 超时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com