Skip to content
Permalink
Browse files

自动下载支持重定向

  • Loading branch information
hankcs committed Nov 26, 2019
1 parent ab0cf20 commit 9751c9879ba70e3920c998eb892af88a680155b4
Showing with 14 additions and 6 deletions.
  1. +14 −6 src/test/java/com/hankcs/hanlp/utility/TestUtility.java
@@ -98,13 +98,14 @@ public static String downloadFile(String fileURL, String savePath)
throws IOException
{
System.err.printf("Downloading %s to %s\n", fileURL, savePath);
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
int responseCode = httpConn.getResponseCode();
HttpURLConnection httpConn = request(fileURL);
while (httpConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || httpConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)
{
httpConn = request(httpConn.getHeaderField("Location"));
}

// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK)
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
@@ -183,10 +184,17 @@ public static String downloadFile(String fileURL, String savePath)
else
{
httpConn.disconnect();
throw new IOException("No file to download. Server replied HTTP code: " + responseCode);
throw new IOException("No file to download. Server replied HTTP code: " + httpConn.getResponseCode());
}
}

private static HttpURLConnection request(String url) throws IOException
{
HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
return httpConn;
}

private static void unzip(String zipFilePath, String destDir, boolean overwrite)
{
System.err.println("Unzipping to " + destDir);

0 comments on commit 9751c98

Please sign in to comment.
You can’t perform that action at this time.