gpt4 book ai didi

java - 如何从android中的URL下载文件的一部分?

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

我正在尝试使用 setRequestProperty("Range","bytes="+ startbytes + "-"+ endbytes); 给定下载 URL 下载文件的一部分;以下代码 fragment 显示了我正在尝试做的事情。

protected String doInBackground(String... aurl) {
int count;
Log.d(TAG,"Entered");
try {

URL url = new URL(aurl[0]);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();

int lengthOfFile = connection.getContentLength();

Log.d(TAG,"Length of file: "+ lengthOfFile);

connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);

问题是,引发了一个异常,显示“建立连接后无法设置请求属性”。请帮我解决这个问题。

最佳答案

选项 1

如果不需要知道内容长度:

[注意,不要调用 connection.getContentLength()。如果你调用它,你会得到异常。如果需要调用,则勾选第二个]

URL url = new URL(aurl[0]);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
//Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
//Your code here to read response data
}

选项 2

如果需要知道内容长度:

URL url = new URL(aurl[0]);
//First make a HEAD call to get the content length
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
int lengthOfFile = connection.getContentLength();
Log.d("ERF","Length of file: "+ lengthOfFile);
connection.disconnect();

//Now that we know the content lenght, make the GET call
connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes=" + 0 + "-" + 1000);
//Note that, response code will be 206 (Partial Content) instead of usual 200 (OK)
if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
//Your code here to read response data

}
}

关于java - 如何从android中的URL下载文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788437/

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