How can I consume an OData4 service in Java using either Olingo or the SDL OData Framework

强颜欢笑 提交于 2019-12-05 07:08:17
Torsten Küpper

The documentation of client side API seems to be a bit neglected by Olingo. But there is an example in the GIT repository at samples / client.

Basically for a GET you do the following:

String serviceUrl = "http://localhost:9080/odata-server-sample/cars.svc"
String entitySetName = "Manufacturers";

ODataClient client = ODataClientFactory.getClient();
URI absoluteUri = client.newURIBuilder(serviceUri).appendEntitySetSegment(entitySetName).build();
ODataEntitySetIteratorRequest<ClientEntitySet, ClientEntity> request = 
client.getRetrieveRequestFactory().getEntitySetIteratorRequest(absoluteUri);
// odata4 sample/server limitation not handling metadata=full
request.setAccept("application/json;odata.metadata=minimal");
ODataRetrieveResponse<ClientEntitySetIterator<ClientEntitySet, ClientEntity>> response = request.execute(); 
ClientEntitySetIterator<ClientEntitySet, ClientEntity> iterator = response.getBody();

while (iterator.hasNext()) {
     ClientEntity ce = iterator.next();
     System.out.println("Manufacturer name: " + ce.getProperty("Name").getPrimitiveValue());
}

Have a look at the sample in the Olingo code base to get further details how to retrieve metadata, process all properties etc.

To do a POST you can do as follows. (Note this is not tested code and the sample Car service is read-only.) First you build up data as ClientEntity. You do e.g. with

ClientComplexValue manufacturer = of.newComplexValue("Manufacturer");
manufacturer.add(of.newPrimitiveProperty("Name", of.newPrimitiveValueBuilder().buildString("Ford")));

Then you send the POST request

ODataEntityCreateRequest<ClientEntity> request = client.getCUDRequestFactory().getEntityCreateRequest(absoluteUri, manufacturer);
ODataEntityCreateResponse<ClientEntity> response = request.execute();

So this is not with POJO classes - the result type is ClientEntity, which presents the data as name/value maps. There is already another unanswered question about that particular topic at Olingo - Create strongly typed POJOs for client library of OData service and I suggest that we turn there to follow up on that.

For SDL OData framework, you can check this Github Test class on how to use OData client.

SDL OData framework is based on the EDM classes and a simple example to get all Products (Product Edm Entity) will look like

// Create and configure the client
DefaultODataClient client = new DefaultODataClient();
client.configure(componentsProvider);

//Build the query
ODataClientQuery query = new BasicODataClientQuery.Builder().withEntityType(Product.class).build();

//Execute the query
List<Object> entities = (List<Object>) client.getEntities(requestProperties, query);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!