使用java访问客户端的odata

时间:2016-01-19 11:52:59

标签: odata sap odata4j olingo

有关使用java程序在客户端访问odata的详细教程。

我有一个SAP ABAP后端API网址,需要身份验证才能访问它。我想在JAVA中访问这个ODATA服务(使用odata4j或olinga)。如果可能,我想详细说明一个例子

任何指针/帮助赞赏

1 个答案:

答案 0 :(得分:0)

我能够找到解决问题的方法。

我尝试访问的Odata服务需要证书,所以我已经包含了所有默认证书

查找以下执行任务的主要方法

public class MainMethod {

public static void main(String[] args) {
        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
                public X509Certificate[] getAcceptedIssuers(){return null;}
                public void checkClientTrusted(X509Certificate[] certs, String authType){}
                public void checkServerTrusted(X509Certificate[] certs, String authType){}
            }};
            // Install the all-trusting trust manager
            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            } catch (Exception e) {
                System.out.println(e);
            }
            ODataConsumer.Builder builder = ODataConsumers.newBuilder(QueryParams.SERVICEURL);
            builder.setClientBehaviors(new BasicAuthenticationBehavior(QueryParams.USER, QueryParams.PW));
            ODataConsumer consumer = builder.build();
            System.out.println(consumer);
            readEntities(consumer);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

private static void readEntities(ODataConsumer consumer) throws Exception {
    try {
        Enumerable<OEntity> entity = consumer.getEntities("TestcaseSet").top(3).execute(); // .first();
        if (entity == null) {
            System.out.println("null-<<<<<");
        }
        Iterator<OEntity> entityLst = entity.iterator();
        while (entityLst.hasNext()) {
            List<OProperty<?>> properties = entityLst.next()
                    .getProperties();
            for (OProperty<?> oProp : properties) {
                System.out.println("Name " + oProp.getName() + "Type "
                        + oProp.getType() + "Value: " + oProp.getValue());
            }
        }
    } catch (RuntimeException runE) {
        System.out.println(runE);
        if ("No elements".equals(runE.getMessage()))
            throw new WrongPersonIdException();
    }
}

}