簡體   English   中英

如何使用Spring RestTemplate在JHipster中訪問Spring REST API

[英]How to access Spring REST API in JHipster with Spring RestTemplate

我已經按照其主頁上的說明設置了一些實體的JHipster。 使用AngularJS的前端效果很好,API頁面也很出色,讓我可以按預期測試我的服務。

現在,我嘗試使用Spring的RestTemplate編寫REST-Client,如下所示:

public List<SomeEntity> getAllEntities(){
     URI uri = URI.create("http://localhost:8080/api/entities");
     HttpHeaders httpHeaders = this.createHeaders("admin", "admin")
     ResponseEntity<SomeEntity[]> responseEntity =  restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<SomeEntity>(httpHeaders), SomeEntity[].class);
     return Arrays.asList(responseEntity.getBody());
}


private HttpHeaders createHeaders(final String username, final String password ){
HttpHeaders headers =  new HttpHeaders(){
      {
         String auth = username + ":" + password;
         byte[] encodedAuth = Base64.encode(
            auth.getBytes(Charset.forName("US-ASCII")) );
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }
   };
   headers.add("Content-Type", "application/json");
   headers.add("Accept", "application/json");

   return headers;
}

但這會導致以下錯誤:[WARN] org.springframework.web.client.RestTemplate-GET請求“ http:// localhost:8080 / api / entities ”導致401(未授權); 調用錯誤處理程序

現在,我不確定是否以及是否需要調整我的HttpHeaders,或者我的簡單基本身份驗證處理方法是否完全錯誤。

身份驗證的方式是錯誤的,似乎您在生成應用時選擇了會話身份驗證,因此這需要基於表單的身份驗證而不是http基本身份驗證,並且它需要能夠存儲會話cookie和CSRF cookie,因此很可能使用common http客戶端。

也許在生成應用程序時選擇xauth令牌身份驗證會更簡單。

一旦開始運行,客戶端將不會與JHipster應用程序在同一主機上運行時,就會出現CORS問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM