0

Java 및 Apache HTTP 클라이언트 (버전 4.3)를 사용하여 Freesound API에 연결하려고합니다.HttpClient를 사용하는 Java의 OAuth2 인증

인증 프로세스를 성공적으로 처리하는 데 응용 프로그램을 가져 오는 데 성공했습니다. 즉, Step 3 of the Freesound API OAuth2 Authentication Procedure에 설명 된대로 액세스 토큰과 새로 고침 토큰에 대한 사용자의 인증 코드를 교환했습니다.

이제 API에서 소리를 다운로드하고 싶습니다.

documentation for downloading sounds from the API에는 현재 Java에서 모방하려고하는 예제 cURL 명령이 있습니다. ,

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

이 새로운 링크는 파일 확장자를 가지고 있지 않기 때문에 :

curl -H "Authorization: Bearer {{access_token}}" 'https://www.freesound.org/apiv2/sounds/14854/download/' 불행하게도, 내가 URL의 파일을 다운로드하는 방법을 알고있는 유일한 방법은 아파치 코 몬즈 IO 라인입니다 권한 부여 헤더를 지정할 수 없으며이 방법을 사용할 수 없습니다.

현재 내 코드가 작동하지 않습니다. 도와주세요!

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

} 

답변

0

그것은

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

VS

request.addHeader("Authentication", authorizationString);

당신은 Apache HttpClient를 사용하여 쉽게 시간을 가질 수 인증인증 수 있습니다 그것은 컴퓨터 간 통신을 위해 설계 되었기 때문입니다.