【问题标题】:OAuth2 Authentication in Java using HttpClient使用 HttpClient 在 Java 中进行 OAuth2 身份验证
【发布时间】:2014-06-19 17:25:39
【问题描述】:

我正在尝试使用 Java 和 Apache HTTP 客户端(4.3 版)连接到 Freesound API

我已成功让我的应用程序成功处理身份验证过程。也就是说,我已经将用户的授权代码换成了访问令牌和刷新令牌,如Step 3 of the Freesound API OAuth2 Authentication Procedure 中所述。

现在我想从 API 下载声音。

documentation for downloading sounds from the API 给出了一个示例 cURL 命令,我现在正尝试在 Java 中模仿它。

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

不幸的是,我知道如何从 URL 下载文件的唯一方法是使用 Apache Commons IO 行:

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

由于这个新链接没有文件扩展名,也不允许我指定授权头,所以我不能使用这种方法。

我的代码目前不起作用。请帮忙!

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

}

【问题讨论】:

    标签: java curl oauth-2.0 apache-httpclient-4.x apache-commons-io


    【解决方案1】:

    可能是Authorization vs Authentication

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

    VS

    request.addHeader("Authentication", authorizationString);

    您可能会更轻松地使用Apache HttpClient,因为它是为计算机到计算机的通信而设计的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      相关资源
      最近更新 更多