1

The url: http://www.teamliquid.net/replay/download.php?replay=1830 is a download link to a .rep file.

My question is: how to download this content in java knowing the name of the original rep file in order to save it with a defined prefix, like path/_.rep

//I was trying to run wget from java but I don't see how to get the original file's name.

4

1 回答 1

1

获取重定向的 URL,

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

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

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

HttpClient 4 - 如何捕获最后一个重定向 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
于 2010-05-13T16:41:51.963 回答