title: How to convert Http url (image URL) to byte buffer or in byte?
body: <p>I have tried some functions to convert url image to byte buffer but it doesn't work. It shows an IOException error</p>
  
  <pre><code>String imagePath = "https://www.clearias.com/up/UPSC-Civil-Services-Mains-Exam-2018-Timetable-V1.png";
  </code></pre>
  
  <p><strong>Try 1:</strong></p>
  
  <pre><code>URL u = new URL(imagePath);
  int contentLength = u.openConnection().getContentLength();
  InputStream openStream = u.openStream();
  byte[] binaryData = new byte[contentLength];
  openStream.read(binaryData);
  ByteBuffer imageBytes = ByteBuffer.wrap(openStream);
  </code></pre>
  
  <p>This shows error when i wrap openStream to ByteBuffer </p>
  
  <blockquote>
    <p>"The method wrap(byte[]) in the type ByteBuffer is not applicable for
    the arguments (InputStream)"</p>
  </blockquote>
  
  <p><strong>Try 2:</strong></p>
  
  <pre><code>    URL url = new URL(imagePath);
      ByteArrayOutputStream output = new ByteArrayOutputStream();
  
      try (InputStream inputStream = url.openStream()) {
          int n = 0;    
          byte[] buffer = new byte[1024];    
          while (-1 != (n = inputStream.read(buffer))) {
              output.write(buffer, 0, n);
          }
      }
      byte[] img = output.toByteArray();    
      ByteBuffer imageBytes = ByteBuffer.wrap(img);    
  </code></pre>
  
  <p>I have also tried this function but it shows this error:</p>
  
  <blockquote>
    <p>java.io.IOException: Server returned HTTP response code: 403 for URL:
    <a href="https://www.clearias.com/up/UPSC-Civil-Services-Mains-Exam-2018-Timetable-V1.png" rel="nofollow noreferrer">https://www.clearias.com/up/UPSC-Civil-Services-Mains-Exam-2018-Timetable-V1.png</a></p>
  </blockquote>
  
  <p><strong>Try 3:</strong>
  And another is </p>
  
  <pre><code>byte[] img = Base64.encodeBase64(IOUtils.toByteArray((new URL(imagePath)).openStream()), true);    
  </code></pre>
  
  <p>This line also gives me error</p>