最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Android中利用HttpClient等库实现网络文件下载

Android crifan 3405浏览 0评论

【问题】

已经获得了Songtaste中歌曲的地址,比如:

http://www.songtaste.com/song/3208674/

中的真实下载地址是:

http://m5.songtaste.com/201212211424/2e8a8a85d93f56370d7fd96b5dc6ff23/5/5c/5cf23a97cef6fad6a464eb506c409dbd.mp3

然后现在想要去下载这样的文件到Android手机的本地某个文件夹中。

【解决过程】

1.其中,关于自动处理Cookie方面的折腾,详见:

【已解决】Android中的HttClient处理过程中,如何自动处理Cookie:发送Cookie,获得返回的Cookie,合并新旧的Cookie

2.参考:

Android download binary file problems

去写代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public Boolean downlodFile(String url, String fullFilename, HttpParams headerParams)
{
    Boolean downloadOk = Boolean.FALSE;
     
    HttpResponse response = getUrlResponse(url, headerParams, null);
 
    if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
         
        HttpEntity respEnt = response.getEntity();
         
        System.out.println("isChunked" + respEnt.isChunked());
        System.out.println("Streaming" + respEnt.isStreaming());
         
        Boolean isStream = respEnt.isStreaming();
        if(isStream)
        {
            try {
                InputStream fileInStream = respEnt.getContent();
                FileOutputStream fileOutStream = new FileOutputStream(new File(fullFilename));
                 
                byte[] tmpBuf = new byte[1024];
                int tmpLen = 0;
                while ( (tmpLen = fileInStream.read(tmpBuf)) > 0 ) {
                    fileOutStream.write(tmpBuf,0, tmpLen);
                }
                 
                downloadOk = Boolean.TRUE;
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
    return downloadOk;
}

最后是可以去获得对应的response,但是结果去创建文件时,出错“java.io.FileNotFoundException: /downloadedMusic.mp3: open failed: EROFS (Read-only file system)”,详细折腾参见:

【已解决】Android中的文件存储位置:java.io.FileNotFoundException: xxx: open failed: EROFS (Read-only file system)

3.有待后续。

转载请注明:在路上 » 【已解决】Android中利用HttpClient等库实现网络文件下载

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.410 seconds, using 22.15MB memory