title: OAuth2 Authentication in Java using HttpClient
body: <p>I'm attempting to connect to the <a href="https://www.freesound.org/help/developers/" rel="nofollow">Freesound API</a> using Java and the Apache HTTP Client (version 4.3).</p>
  
  <p>I have succeeded in getting my application to successfully handle the authentication process.  That is, I have exchanged the user's authorization code for an access token and refresh token, as outlined in <a href="http://www.freesound.org/docs/api/authentication.html#step-3" rel="nofollow">Step 3 of the Freesound API OAuth2 Authentication Procedure</a>.</p>
  
  <p><strong>Now I wish to download sounds from the API.</strong></p>
  
  <p>The <a href="http://www.freesound.org/docs/api/resources_apiv2.html#download-sound-oauth2-required" rel="nofollow">documentation for downloading sounds from the API</a> gives an example cURL command that I am now trying to mimic in Java.</p>
  
  <p><code>curl -H "Authorization: Bearer {{access_token}}" 'https://www.freesound.org/apiv2/sounds/14854/download/'</code></p>
  
  <p>Unfortunately, the only way I know how to download files from URLs is with the Apache Commons IO line: </p>
  
  <p><code>org.apache.commons.io.FileUtils.copyURLToFile(URL, File)</code></p>
  
  <p>Since this new link does not have a file extension, nor does it allow me to specify the Authorization Header, I cannot use this method.</p>
  
  <p>My code currently  does not work. Please help!</p>
  
  <pre><code>private static void downloadSound() {
  
      // the output stream to save .wav file
      FileOutputStream out;
  
      // the file to save
      File f = new File("test.wav");
  
      // initializes http client and builds authorization header
      HttpResponse res;
      CloseableHttpClient httpclient = HttpClients.createDefault();
      String authorizationString = "Bearer " + accessToken;
  
      try {
  
          // assigns url and authorization header to GET request
          HttpGet request = new HttpGet(
                  URI.create("https://www.freesound.org/apiv2/sounds/14854/download/"));
          request.addHeader("Authentication", authorizationString);
  
          // sends GET request
          res = httpclient.execute(request);
  
         // downloads file
          FileOutputSTream out = new FileOutputStream(f);
          int read = 0;
          byte[] bytes = new byte[1024];
  
          while ((read = res.getEntity().getContent().read(bytes)) != -1) {
              out.write(bytes, 0, read);
          }
  
          System.out.println("Done!");
  
        // closes input/output streams
          res.getEntity().getContent().close();
          out.close();
  
      } catch (IOException e) {
          e.printStackTrace();
      }
  
  }
  </code></pre>