Fix small bug in Downloader
[nikiroo-utils.git] / src / be / nikiroo / utils / Downloader.java
index e01ec1dcc24cb3abccc28bb3618b62edf0ad7a54..2919ff01bf551d2d99eca89883c42a1c2e744f51 100644 (file)
@@ -186,23 +186,35 @@ public class Downloader {
                        }
 
                        if (requestData != null) {
-                               OutputStreamWriter writer = new OutputStreamWriter(
-                                               conn.getOutputStream());
-
-                               writer.write(requestData.toString());
-                               writer.flush();
-                               writer.close();
+                               OutputStreamWriter writer = null;
+                               try {
+                                       writer = new OutputStreamWriter(conn.getOutputStream());
+                                       writer.write(requestData.toString());
+                                       writer.flush();
+                               } finally {
+                                       if (writer != null) {
+                                               writer.close();
+                                       }
+                               }
                        }
                }
 
                conn.connect();
 
                // Check if redirect
-               if (conn instanceof HttpURLConnection
-                               && ((HttpURLConnection) conn).getResponseCode() / 100 == 3) {
-                       String newUrl = conn.getHeaderField("Location");
-                       return open(new URL(newUrl), originalUrl, currentReferer,
-                                       cookiesValues, postParams, getParams, oauth);
+               if (conn instanceof HttpURLConnection) {
+                       int repCode = 0;
+                       try {
+                               // Can fail in some circumstances
+                               repCode = ((HttpURLConnection) conn).getResponseCode();
+                       } catch (IOException e) {
+                       }
+
+                       if (repCode / 100 == 3) {
+                               String newUrl = conn.getHeaderField("Location");
+                               return open(new URL(newUrl), originalUrl, currentReferer,
+                                               cookiesValues, postParams, getParams, oauth);
+                       }
                }
 
                InputStream in = conn.getInputStream();