【问题标题】:Downloading multimedia content in java from php pages从php页面下载java中的多媒体内容
【发布时间】:2010-05-13 15:50:05
【问题描述】:

网址:http://www.teamliquid.net/replay/download.php?replay=1830 是 .rep 文件的下载链接。

我的问题是:如何在知道原始 rep 文件的名称的情况下在 java 中下载此内容,以便使用定义的前缀保存它,例如 path/_.rep

//我试图从 java 中运行 wget,但我没有看到如何获取原始文件的名称。

【问题讨论】:

    标签: java php download wget multimedia


    【解决方案1】:

    获取重定向的 URL,

    http://www.teamliquid.net/replay/upload/coco%20vs%20snssoflsekd.rep

    您可以从此 URL 获取文件名。

    获取重定向的 URL 很棘手。请参阅我对此问题的回答,了解如何使用 Apache HttpClient 4 进行操作,

    HttpClient 4 - how to capture last redirect URL

    编辑:这是一个使用 HttpClient 4.0 的示例,

    String url = "http://www.teamliquid.net/replay/download.php?replay=1830";
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpContext context = new BasicHttpContext(); 
    HttpResponse response = httpClient.execute(httpget, context); 
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
        throw new IOException(response.getStatusLine().toString());
    HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute( 
        ExecutionContext.HTTP_REQUEST);
    String currentUrl = URLDecoder.decode(currentReq.getURI().toString(), "UTF-8");
    int i = currentUrl.lastIndexOf('/');
    String fileName = null;
    if (i < 0) {
        fileName = currentUrl;
    } else {
        fileName = currentUrl.substring(i+1);
    }
    OutputStream os = new FileOutputStream("/tmp/" + fileName);
    InputStream is = response.getEntity().getContent();
    byte[] buf = new byte[4096];  
    int read;  
    while ((read = is.read(buf)) != -1) {  
       os.write(buf, 0, read);  
    }  
    os.close();
    

    运行这段代码后,我得到了这个文件,

    /tmp/coco vs snssoflsekd.rep
    

    【讨论】:

    • 非常感谢,您重新表述了问题并给出了解决方案。 HttpClient也可以下载内容吗?
    猜你喜欢
    • 1970-01-01
    • 2016-05-01
    • 2014-05-18
    • 1970-01-01
    • 2010-10-25
    • 2011-10-17
    • 2018-04-25
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多