title: Download binary file from OKHTTP
body: <p>I am using OKHTTP client for networking in my android application.</p>
  <p><a href="https://stackoverflow.com/questions/25367888/upload-binary-file-with-okhttp-from-resources">This</a> example shows how to upload binary file. I would like to know how to get inputstream of binary file downloading with OKHTTP client.</p>
  <p>Here is the listing of the example :</p>
  <pre><code>public class InputStreamRequestBody extends RequestBody {
  
      private InputStream inputStream;
      private MediaType mediaType;
  
      public static RequestBody create(final MediaType mediaType, 
              final InputStream inputStream) {
          return new InputStreamRequestBody(inputStream, mediaType);
      }
  
      private InputStreamRequestBody(InputStream inputStream, MediaType mediaType) {
          this.inputStream = inputStream;
          this.mediaType = mediaType;
      }
  
      @Override
      public MediaType contentType() {
          return mediaType;
      }
  
      @Override
      public long contentLength() {
          try {
              return inputStream.available();
          } catch (IOException e) {
              return 0;
          }
      }
  
      @Override
      public void writeTo(BufferedSink sink) throws IOException {
          Source source = null;
          try {
              source = Okio.source(inputStream);
              sink.writeAll(source);
          } finally {
              Util.closeQuietly(source);
          }
      }
  }
  </code></pre>
  <p>Current code for simple get request is:</p>
  <pre><code>OkHttpClient client = new OkHttpClient();
  request = new Request.Builder().url(&quot;URL string here&quot;)
                      .addHeader(&quot;X-CSRFToken&quot;, csrftoken)
                      .addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
                      .build();
  response = getClient().newCall(request).execute();
  </code></pre>
  <p>Now how do I convert the response to <code>InputStream</code>. Something similar to response from <code>Apache HTTP Client</code> like this for <code>OkHttp</code> response:</p>
  <pre><code>InputStream is = response.getEntity().getContent();
  </code></pre>
  <hr />
  <h3>EDIT</h3>
  <p>Accepted answer from below.
  My modified code:</p>
  <pre><code>request = new Request.Builder().url(urlString).build();
  response = getClient().newCall(request).execute();
  
  InputStream is = response.body().byteStream();
  
  BufferedInputStream input = new BufferedInputStream(is);
  OutputStream output = new FileOutputStream(file);
  
  byte[] data = new byte[1024];
  
  long total = 0;
  
  while ((count = input.read(data)) != -1) {
      total += count;
      output.write(data, 0, count);
  }
  
  output.flush();
  output.close();
  input.close();
  </code></pre>