2017-08-31 62 views
0

我正在嘗試使用以下代碼在我的Spring Rest應用程序中擊中一個Microsoft Flow POST URL,但它給了我401個錯誤。 我的代碼:當使用授權標頭髮送時,Spring RestTemplate會給出401未授權錯誤

@RequestMapping(value = "/hookslistner", method = RequestMethod.POST) 
    public ResponseEntity<Void> recieveWebhook(@RequestBody InventorySystemModel inventory, 
      @RequestHeader("event") String event, 
      @RequestHeader("Authorization") String authorization) { 
// authorization = "Basic <Base64 encoded value of username:pwd>" 

     RestTemplate restTemplate = new RestTemplate(); 

     org.springframework.http.HttpHeaders httpHeaders = new org.springframework.http.HttpHeaders(); 

     String url = "https://prod-01.centralindia.logic.azure.com/workflows/835348<hiding rest of part>";   
     String headerName = "Authorization"; 
     httpHeaders.add(headerName, authorization); 
     httpHeaders.add("Content-Type", "application/json"); 
     HttpEntity<String> requestEntity = new HttpEntity<>("Headers", httpHeaders); 
     System.out.println(">>>>>>>" + restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class).getBody()); 
    } 

錯誤:

SEVERE: Servlet.service() for servlet [webhooks] in context with path [/inventoryhooks] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 401 Unauthorized] with root cause 
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized 
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 
. 
. 
. 

是不是因爲我的目標URL爲https和我的本地是http?

任何人都可以指出我哪裏出了問題?

+0

此時被拋出的異常?在RestTemplate或進入方法之前? –

+0

at'restTemplate.exchange' –

回答

0

兩點爲您檢查這個問題:

  1. 如果目標服務器是一個HTTP服務器,那麼你不應該在URL中使用https。
  2. 確保authorization值爲base64編碼。

更新:

由於目標服務器是HTTPS服務器,問題是你有沒有配置ssl信息到RestTempalte。您可以參考下面的代碼片段獲得SSL restTemplate:

@Configuration 
public class RestClientConfig { 
    @Bean 
    public RestOperations restOperations(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception { 
     return new RestTemplate(clientHttpRequestFactory); 
    } 

    @Bean 
    public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) { 
     return new HttpComponentsClientHttpRequestFactory(httpClient); 
    } 

    @Bean 
    public HttpClient httpClient(@Value("${keystore.file}") String file, @Value("${keystore.pass}") String password) throws Exception { 
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
     FileInputStream inStream = new FileInputStream(file); 
     try { 
      trustStore.load(inStream, password.toCharArray()); 
     } finally { 
      inStream.close(); 
     } 

     SSLContext sslcontext = 
       SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); 
     SSLConnectionSocketFactory sslsf = 
       new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, 
               null); 
     return HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
    } 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

測試用例:

@RunWith(SpringRunner.class) 
@ContextConfiguration(classes = RestClientConfig.class) 
public class RestClientTest { 

    @Autowired 
    private RestOperations rest; 

    private HttpHeaders getHeaders(){ 
     String plainCredentials="admin:admin"; 
     String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes()); 

     HttpHeaders headers = new HttpHeaders(); 
     headers.add("Authorization", "Basic " + base64Credentials); 
     return headers; 
    } 

    @Test 
    public void test() { 
     HttpEntity<String> request = new HttpEntity<String>(getHeaders()); 
     ResponseEntity<String> response = rest.exchange(url, HttpMethod.GET, request, String.class); 
     System.out.println(response.getBody()); 
    } 
} 
+0

它是Microsoft Flow的REST URL,並且是https,授權也有base64編碼值。還是同樣的問題... –

+0

現在我收到這個錯誤,我不知道有任何SSL操作或技巧,請幫助! 'SEVERE:在路徑[/ inventoryhooks]上下文中servlet [webhooks]的Servlet.service()拋出異常[Request processing failed;嵌套異常是org.springframework.web.client.ResourceAccessException:「https://prod-03.centralindia.logic.azure.com/workflows/a 」POST請求上的I/O錯誤:sun.security.validator。 ValidatorException:PKIX路徑構建失敗:sun.security.provider.certpath.SunCertPathBuilderException:無法找到所需目標的有效證書路徑 –