Apache olingo基本认证编码问题

问题描述:

我使用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始终将它用于响应对象构建,则可能不可能)

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