javaolingo

How to Add Header to ODataClient (Apache Olingo)?


I am having a trouble accessing the odata service, because it requires a specific header, and I couldn't add it directly on the ODataClient, does anyone have any idea on how to solve my problem?

Psuedo Code:

ODataClient client = ODataClientFactory.getClient(); 
client.addHeader("Header","123456789"); // <---- this code is what I am seeking
URI customersUri = client.newURIBuilder("uri/northwindmodel.svc")
          .appendEntitySetSegment("Customers").build();
ODataRetrieveResponse<ODataEntitySetIterator<ODataEntitySet, ODataEntity>> response
 = client.getRetrieveRequestFactory().getEntitySetIteratorRequest(customersUri).execute();

Dependency:

<dependency>
    <groupId>org.apache.olingo</groupId>
    <artifactId>odata-client-core</artifactId>
    <version>4.5.0</version>
</dependency>

Solution

  • The ODataClient does not have and API to set additional headers, probably because it directly doesn't own HttpClient directly. Its owned my AbstractODataRequestclass, so you have APIs to set additonal headers per HTTP request.

    In your case you can use addCustomHeader method in ODataRequest.

    Ex. Your sample code can be refactored in the following way to achieve the goal.

    ODataClient client = ODataClientFactory.getClient(); 
    // client.addHeader("Header","123456789"); // <---- this code is what I am seeking
    URI customersUri = client.newURIBuilder("uri/northwindmodel.svc")
            .appendEntitySetSegment("Customers").build();
    
    ODataEntitySetIteratorRequest<ClientEntitySet, ClientEntity> entitySetIteratorRequest =
            client.getRetrieveRequestFactory().getEntitySetIteratorRequest(qryUri);
    
    entitySetIteratorRequest.addCustomHeader("Custom-Header-key", "Custom-Header-Value");
    
    ODataRetrieveResponse<ClientEntitySetIterator<ClientEntitySet, ClientEntity>> response = entitySetIteratorRequest.execute();