gpt4 book ai didi

java - HttpURLConnection 请求被两次发送到服务器以下载文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:19:23 27 4
gpt4 key购买 nike

以下是我从服务器下载文件的android代码。

private String executeMultipart_download(String uri, String filepath)
throws SocketTimeoutException, IOException {
int count;
System.setProperty("http.keepAlive", "false");
// uri="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTzoeDGx78aM1InBnPLNb1209jyc2Ck0cRG9x113SalI9FsPiMXyrts4fdU";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
Log.d("File Download", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(filepath);
byte data[] = new byte[1024];
long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
httpStatus = connection.getResponseCode();
String statusMessage = connection.getResponseMessage();
connection.disconnect();
return statusMessage;
}

我已经调试了这段代码。即使它两次访问服务器,该函数也只被调用一次。他们在这段代码中有什么错误吗?

谢谢

最佳答案

你的错误在于这一行:

url.openStream()

如果我们转到 grepcode 到这个函数的源代码,那么我们将看到:

public final InputStream openStream() throws java.io.IOException {
return openConnection().getInputStream();
}

但是你已经打开了连接,所以你打开了两次连接。

作为解决方案,您需要将 url.openStream() 替换为 connection.getInputStream()

因此,您的剪断遗嘱如下所示:

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
Log.d("File Download", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(connection.getInputStream());

关于java - HttpURLConnection 请求被两次发送到服务器以下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38583020/

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