问题描述
我想下载此文件(http://github.com/downloads/TheHolyWaffle/ChampionHelper/ChampionHelper-4.jar)用下面的方法,它似乎并没有工作。我收到一个空/损坏的文件。
I'm trying to download this file (http://github.com/downloads/TheHolyWaffle/ChampionHelper/ChampionHelper-4.jar) with the following method and it doesn't seem to work. I'm getting an empty/corrupt file.
String link = "http://github.com/downloads/TheHolyWaffle/ChampionHelper/ChampionHelper-4.jar";
String fileName = "ChampionHelper-4.jar";
URL url = new URL(link);
URLConnection c = url.openConnection();
c.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 1.2.30703)");
InputStream input;
input = c.getInputStream();
byte[] buffer = new byte[4096];
int n = -1;
OutputStream output = new FileOutputStream(new File(fileName));
while ((n = input.read(buffer)) != -1) {
if (n > 0) {
output.write(buffer, 0, n);
}
}
output.close();
不过,我可以成功地从我的Dropbox下载以下文件(http://dl.dropbox.com/u/13226123/ChampionHelper-4.jar)用同样的方法。
所以,在某种程度上Github的人都知道,我不是要下载一个文件,普通用户。我已经试图改变用户代理,但这并没有帮助。
So somehow Github knows that I'm not a regular user trying to download a file. I already tried to change the user agent, but that didn't help either.
所以,我应该怎么下载是使用Java我Github上的帐户托管的文件?
So how should I download a file that is hosted on my Github account using Java?
编辑:我试着使用Apache Commons-IO了这一点,但我得到相同的效果,空/损坏的文件
I tried to use the apache commons-io for this but I get the same effect, an empty/corrupt file.
推荐答案
这一次做的工作:
public class Download {
private static boolean isRedirected( Map<String, List<String>> header ) {
for( String hv : header.get( null )) {
if( hv.contains( " 301 " )
|| hv.contains( " 302 " )) return true;
}
return false;
}
public static void main( String[] args ) throws Throwable
{
String link =
"http://github.com/downloads/TheHolyWaffle/ChampionHelper/" +
"ChampionHelper-4.jar";
String fileName = "ChampionHelper-4.jar";
URL url = new URL( link );
HttpURLConnection http = (HttpURLConnection)url.openConnection();
Map< String, List< String >> header = http.getHeaderFields();
while( isRedirected( header )) {
link = header.get( "Location" ).get( 0 );
url = new URL( link );
http = (HttpURLConnection)url.openConnection();
header = http.getHeaderFields();
}
InputStream input = http.getInputStream();
byte[] buffer = new byte[4096];
int n = -1;
OutputStream output = new FileOutputStream( new File( fileName ));
while ((n = input.read(buffer)) != -1) {
output.write( buffer, 0, n );
}
output.close();
}
}
这篇关于从GitHub使用Java下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!