Fix small bug in Downloader
[nikiroo-utils.git] / src / be / nikiroo / utils / Downloader.java
index a8a591a363958412a73eb6ef042d38ba33ae1cf9..2919ff01bf551d2d99eca89883c42a1c2e744f51 100644 (file)
@@ -63,6 +63,10 @@ public class Downloader {
         *            the new traces handler
         */
        public void setTraceHandler(TraceHandler tracer) {
+               if (tracer == null) {
+                       tracer = new TraceHandler(false, false, false);
+               }
+
                this.tracer = tracer;
        }
 
@@ -182,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();