使用Java从Github下载二进制文件

Ber*_*ter 6 java binary github urlconnection download

我正在尝试使用以下方法下载此文件(http://github.com/downloads/TheHolyWaffle/ChampionHelper/ChampionHelper-4.jar),它似乎不起作用.我收到一个空/损坏的文件.

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();
Run Code Online (Sandbox Code Playgroud)

但我可以使用相同的方法从我的Dropbox(http://dl.dropbox.com/u/13226123/ChampionHelper-4.jar)成功下载以下文件.

所以不知何故Github知道我不是一个试图下载文件的普通用户.我已经尝试更改用户代理,但这也没有帮助.

那么我应该如何使用Java下载托管在我的Github帐户上的文件?

编辑:我试图使用apache commons-io,但我得到相同的效果,一个空/损坏的文件.

Aub*_*bin 2

这个人做的工作:

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();
   }
}
Run Code Online (Sandbox Code Playgroud)