title: Downloading corrupted files with OkHttp
body: <p>The method I wrote to download files always produce corrupted files.</p>
  <pre><code>public static String okDownloadToFileSync(final String link, final String fileName, final boolean temp, DownloadStatusManager statusManager, ErrorDisplayerInterface errorDisplayerInterface) {
  
      Request request = new Request.Builder()
              .url(link)
              .build();
  
  
      OkHttpClient client = Api.getInstance().getOkHttpClient();
      OutputStream output = null;
      InputStream input = null;
  
      try {
  
          Response response = client.newCall(request).execute();
  
          //Add the file length to the statusManager
          final int contentLength = Integer.parseInt(response.header(&quot;Content-Length&quot;));
          if (statusManager != null) {
              statusManager.add(Hash.md5(link), contentLength);
          }
  
          //Get content type to know extension
          final String contentType = response.header(&quot;Content-Type&quot;);
          final String ext = contentTypeMap.get(contentType);
  
          Log.i(TAG, link + &quot;\n --&gt; contentType = &quot; + contentType + &quot;\n --&gt; ext = &quot; + ext);
  
          if (ext == null) {
              Log.e(TAG, &quot;-----------\next is null, seems like there is a problem with that url : \n         &quot; + link + &quot;\n----------&quot;);
              return null;
          } else if (ext.equals(&quot;json&quot;)) {
              Log.e(TAG, &quot;-----------\ndownloadable file seems to be a json, seems like there is a problem with that url : \n         &quot; + link + &quot;\n----------&quot;);
              return null;
          }
  
          //Check if file already exists
          if (!temp &amp;&amp; fileName != null) {
              File test = new File(M360Application.getContext().getFilesDir(), fileName + &quot;.&quot; + ext);
              if (test.exists()) {
                  Log.i(TAG, &quot;File exists ! : &quot; + test.getPath());
                  test.delete();
                  //return test.getAbsolutePath();
              }
          }
  
          // expect HTTP 200 OK, so we don't mistakenly save error report instead of the file
          if (!response.isSuccessful()) {
              errorDisplayerInterface.popWarn(null, &quot;Error while downloading &quot; + link, &quot;connection.getResponseCode() != HttpURLConnection.HTTP_OK&quot;);
              return null;
          }
  
          input = response.body().byteStream();
  
          File file;
          if (temp) {
              file = File.createTempFile(UUID.randomUUID().toString(), ext, M360Application.getContext().getCacheDir());
          } else {
              file = new File(M360Application.getContext().getFilesDir(), fileName + &quot;.&quot; + ext);
          }
  
  
          output = new FileOutputStream(file);
          
          output.write(response.body().bytes());
  
  //            byte data[] = new byte[4096];
  //            long total = 0;
  //            int count;
  //            while ((count = input.read(data)) != -1) {
  //                output.write(data, 0, count);
  //                total++;
  //
  //                if (statusManager != null) {
  //                    statusManager.update(Hash.md5(link), contentLength - total);
  //                }
  //           }
  
          return file.getAbsolutePath();
      } catch (IOException e) {
          e.printStackTrace();
          errorDisplayerInterface.popError(null, e);
  
      } finally {
          if (statusManager != null) {
              statusManager.finish(Hash.md5(link));
          }
          try {
              if (output != null)
                  output.close();
              if (input != null)
                  input.close();
          } catch (IOException ignored) {
              ignored.printStackTrace();
          }
  
      }
      return null;
  }
  </code></pre>
  <p>I access these file via adb, transfer them to my sccard, and there I see that they seem to have the proper size, but has no type according to for instance Linux <code>file</code> command.</p>
  <p>Would you know what is missing and how to fix it?</p>
  <p>Thank you.</p>
  <hr />
  <h1>Edit</h1>
  <p>Simpler version of the code ( but the bug is the same )</p>
  <pre><code>public static String okioDownloadToFileSync(final String link, final String fileName) throws IOException {
  
      Request request = new Request.Builder()
              .url(link)
              .build();
  
  
      OkHttpClient client = Api.getInstance().getOkHttpClient();
      Response response = client.newCall(request).execute();
  
      final int contentLength = Integer.parseInt(response.header(&quot;Content-Length&quot;));
  
      //Get content type to know extension
      final String contentType = response.header(&quot;Content-Type&quot;);
      final String ext = contentTypeMap.get(contentType);
  
      // expect HTTP 200 OK, so we don't mistakenly save error report instead of the file
      if (!response.isSuccessful()) {
          return null;
      }
  
      File file = new File(M360Application.getContext().getFilesDir(), fileName + &quot;.&quot; + ext);
  
      BufferedSink sink = Okio.buffer(Okio.sink(file));
      sink.writeAll(response.body().source());
      sink.close();
  
      Log.i(TAG, &quot;file.length : &quot; + file.length() + &quot; | contentLength : &quot; + contentLength);
  
      return file.getAbsolutePath();
  
  }
  </code></pre>
  <blockquote>
  <p>The log : <code>file.length : 2485394 | contentLength : 1399242</code></p>
  </blockquote>
  <hr />
  <h1>Solution</h1>
  <p>The problem was that I was getting the <code>OkHttpClient</code> from my API singleton, which was used by retrofit and had multiples interceptors. Those interceptors were polluting the response.</p>
  <p>So I <code>OkHttpClient client = Api.getInstance().getOkHttpClient();</code> became <code>OkHttpClient client = new OkHttpClient.Builder().build();</code> and everything is now ok !</p>
  <p>Thanks a lot. I'm dividing the method into smaller pieces right now.</p>