Skip to content

Commit

Permalink
Merge pull request #30 from caseif/feature/redirects
Browse files Browse the repository at this point in the history
Update to properly handle 301/302 redirects
  • Loading branch information
gravitylow committed Sep 20, 2016
2 parents 939e624 + a857fd9 commit 3912c05
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Expand Up @@ -4,7 +4,7 @@

<groupId>net.gravitydevelopment.updater</groupId>
<artifactId>updater</artifactId>
<version>2.3</version>
<version>2.4</version>
<packaging>jar</packaging>
<name>Updater</name>
<url>http://forums.bukkit.org/threads/updater-2-0-easy-safe-and-policy-compliant-auto-updating-for-your-plugins-new.96681/</url>
Expand Down
32 changes: 30 additions & 2 deletions src/main/java/net/gravitydevelopment/updater/Updater.java
@@ -1,6 +1,7 @@
package net.gravitydevelopment.updater;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
Expand Down Expand Up @@ -30,7 +31,7 @@
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
*
* @author Gravity
* @version 2.3
* @version 2.4
*/

public class Updater {
Expand Down Expand Up @@ -390,7 +391,7 @@ private void downloadFile() {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL fileUrl = new URL(this.versionLink);
URL fileUrl = followRedirects(this.versionLink);
final int fileLength = fileUrl.openConnection().getContentLength();
in = new BufferedInputStream(fileUrl.openStream());
fout = new FileOutputStream(new File(this.updateFolder, file.getName()));
Expand Down Expand Up @@ -430,6 +431,33 @@ private void downloadFile() {
}
}

private URL followRedirects(String location) throws IOException {
URL resourceUrl, base, next;
HttpURLConnection conn;
String redLoc;
while (true) {
resourceUrl = new URL(location);
conn = (HttpURLConnection) resourceUrl.openConnection();

conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("User-Agent", "Mozilla/5.0...");

switch (conn.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
redLoc = conn.getHeaderField("Location");
base = new URL(location);
next = new URL(base, redLoc); // Deal with relative URLs
location = next.toExternalForm();
continue;
}
break;
}
return conn.getURL();
}

/**
* Remove possibly leftover files from the update folder.
*/
Expand Down

0 comments on commit 3912c05

Please sign in to comment.