views:

35

answers:

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.

+1  A: 

Get the redirected URL,

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

You can get the filename from this URL.

It's tricky to get the redirected URL. See my answer to this question on how to do it with Apache HttpClient 4,

http://stackoverflow.com/questions/1456987/httpclient-4-how-to-capture-last-redirect-url/1457173#1457173

EDIT: Here is a sample using 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();

After running this code, I get this file,

/tmp/coco vs snssoflsekd.rep
ZZ Coder
Thanks a lot, you rephrased the problem and gave the solution. Can HttpClient download content as well?
jmcejuela
See my edit with working code.
ZZ Coder