2017-10-06 94 views
1

我使用Apache olingo開發OData客戶端,憑據包含本地字符,應以UTF-8讀取「授權」標頭的Base64編碼。 第一種方式去在標準建議的Olingo:Apache olingo基本認證編碼問題

EdmEnabledODataClient client = ODataClientFactory.getEdmEnabledClient(endpointURI, ContentType.JSON); 
client.getConfiguration().setHttpClientFactory(new BasicAuthHttpClientFactory(username, password)); 

但是這並沒有對我沒用,因爲Olingo讀取Base64編碼的「用戶名」和「密碼」字節在US-ASCII字符集,並我的用戶名變成了??? 。 在HTTP客戶端級別上,有一種方法可以將字符集傳遞到org.apache.http.impl.auth.BasicSchemeFactory,但我發現無法在Olingo級別對其進行自定義。

我的第二次嘗試添加原始標題:

URI searchURI = client.newURIBuilder(endpointURI) 
      .appendEntitySetSegment(segment) 
      .top(10) 
      .addQueryOption(QueryOption.FORMAT, "json")   
      .build(); 
    ODataEntitySetRequest<ClientEntitySet> request = client.getRetrieveRequestFactory().getEntitySetRequest(searchURI); 
    String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes(StandardCharsets.UTF_8)); 
      request.addCustomHeader("Authorization", "Basic "+ auth); 
    ODataRetrieveResponse<ClientEntitySet> response = request.execute(); 

但看來,Olingo實際發送request.execute號召下2個HTTP請求。首先是數據,它包含我的頭文件,通過授權並返回數據 - 很好。但是第二個請求是元數據,沒有授權標頭,並且返回401 Unauthorized。所以最終的結果是例外。 我需要一種方法來添加基本身份驗證。這將通過完整的Olingo請求週期(多個http請求,並使用UTF-8字符集來處理我的憑證),或者以某種方式禁用元數據調用(如果Olingo始終將它用於響應對象構建,則可能不可能)

回答

1

Found一個解決方案,但仍然對Olingo推薦的方式感興趣

  EdmEnabledODataClient client = ODataClientFactory.getEdmEnabledClient(endpointURI, ContentType.JSON); 
      final String auth = Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes(StandardCharsets.UTF_8)); 
      client.getConfiguration().setHttpClientFactory(new DefaultHttpClientFactory() { 
       @SuppressWarnings("deprecation") 
       @Override 
       public DefaultHttpClient create(HttpMethod method, URI uri) { 
        final DefaultHttpClient client = super.create(method, uri); 
        client.addRequestInterceptor(new HttpRequestInterceptor() { 
         @Override 
         public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { 
          request.addHeader("Authorization", "Basic " + auth); 
        } 
       }); 
       return client; 
      } 
     });