104

私はRestTemplateと基本的にREST APIもまったく初めてです。Jira REST API 経由でアプリケーションのデータを取得したいのですが、401 Unauthorized が返されます。jira rest api ドキュメントに関する記事が見つかりましたが、この例では curl でコマンド ラインを使用しているため、これを Java に書き換える方法がよくわかりません。書き直し方法の提案やアドバイスをいただければ幸いです。

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"

スプリング レスト テンプレートを使用して Java に変換します。ZnJlZDpmcmVk は、base64 でエンコードされたユーザー名:パスワードの文字列です。どうもありがとうございました。

4

9 に答える 9

180

このサイトの例を参考にすると、ヘッダー値を入力してヘッダーをテンプレートに渡すのが最も自然な方法だと思います。

これはヘッダーに記入することAuthorizationです:

String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

これは、REST テンプレートにヘッダーを渡すためのものです。

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();
于 2014-02-20T21:50:53.703 に答える
25

(おそらく) spring-boot をインポートしない最も簡単な方法。

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));
于 2018-03-15T11:11:58.193 に答える
17

Spring Boot のTestRestTemplate実装を次のように参照します。

https://github.com/spring-projects/spring-boot/blob/v1.2.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/test/TestRestTemplate.java

特に、次の addAuthentication() メソッドを参照してください。

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}

同様に、自分でRestTemplate簡単に作成できます

次のように継承TestRestTemplateします。

https://github.com/izeye/samples-spring-boot-branches/blob/rest-and-actuator-with-security/src/main/java/samples/springboot/util/BasicAuthRestTemplate.java

于 2015-03-11T07:54:36.450 に答える