Search code examples
javacurloauth-2.0apache-httpclient-4.xapache-commons-io

OAuth2 Authentication in Java using HttpClient


I'm attempting to connect to the Freesound API using Java and the Apache HTTP Client (version 4.3).

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 Step 3 of the Freesound API OAuth2 Authentication Procedure.

Now I wish to download sounds from the API.

The documentation for downloading sounds from the API gives an example cURL command that I am now trying to mimic in Java.

curl -H "Authorization: Bearer {{access_token}}" 'https://www.freesound.org/apiv2/sounds/14854/download/'

Unfortunately, the only way I know how to download files from URLs is with the Apache Commons IO line:

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

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.

My code currently does not work. Please help!

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();
    }

}

Solution

  • It might be Authorization vs Authentication

    curl -H "Authorization: Bearer {{access_token}}"

    VS

    request.addHeader("Authentication", authorizationString);

    You might have an easier time using Apache HttpClient, as it is designed for computer to computer communication.