欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

liferay JSON Web服务接口调用

程序员文章站 2022-07-15 13:22:20
...

 

提供三种服务调用方式,分别为javaScript、 curl和URL,下面对两种使用场景进行示描述。

 

1. 在portlet下使用javaScript调用JSON WEB服务

1.1. 通过JavaScript获取用户JSON Web服务调用

Liferay.Service(

    '/user/get-user-by-email-address`,

    {

        companyId: Liferay.ThemeDisplay.getCompanyId(),

        emailAddress: '[email protected]`

    },

    function(obj) {

        console.log(obj);

    }

);

 

1.2. 通过JavaScript添加用户JSON Web服务调用

Liferay.Service(
    '/user/add-user',
    {
        companyId: Liferay.ThemeDisplay.getCompanyId(),
        autoPassword: false,
        password1: 'test',
        password2: 'test',
        autoScreenName: false,
        screenName: 'joe.bloggs',
        emailAddress: '[email protected]',
        facebookId: 0,
        openId: '',
        locale: 'en_US',
        firstName: 'Joe',
        middleName: 'T',
        lastName: 'Bloggs',
        prefixId: 0,
        suffixId: 0,
        male: true,
        birthdayMonth: 1,
        birthdayDay: 1,
        birthdayYear: 1970,
        jobTitle: 'Tester',
        groupIds: null,
        organizationIds: null,
        roleIds: null,
        userGroupIds: null,
        sendEmail: false,
        serviceContext: {assetTagNames: ['test']}
    },
    function(obj) {
        console.log(obj);
    }
);

 

2. 在java中通过url调用JSON WEB服务

2.1. 身份验证处理

示意代码如下:


/**

 * api认证帐号

 */

private static String username = "[email protected]";

/**

 * api认证密码

 */

private static String password = "test";



public static String httpGet(String pathUrl){

    BASE64Encoder encoder = new BASE64Encoder();

    HttpURLConnection httpConn = null;

    InputStream is = null;

    ByteArrayOutputStream baos = null;

    String body = null;

    try {

        URL url = new URL(pathUrl);

        httpConn = (HttpURLConnection) url.openConnection();

        //登录认证信息放入header中

        String token = TestApi.username + ":" + TestApi.password;

        String authorString = "Basic " + encoder.encode(token.getBytes());

        httpConn.setRequestProperty("Authorization", authorString);

        httpConn.connect();

        is = httpConn.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));

        String reader = null;

        StringBuilder builder = new StringBuilder();

        while ((reader = br.readLine()) != null) {

            builder.append(reader);

        }

        body = builder.toString();

    }catch(IOException ex){

        ex.printStackTrace();

        if(httpConn==null){

            return null;

        }

        try {

            System.out.println("error code:"+httpConn.getResponseCode());

            if(httpConn.getResponseCode() != 404)

                is=httpConn.getErrorStream();

            if(is != null) {

                BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));

                String reader = null;

                StringBuilder builder = new StringBuilder();

                while ((reader = br.readLine()) != null) {

                    builder.append(reader);

                }

                body = builder.toString();

            }

        } catch (IOException e) {}

    }catch (Exception ex){

        ex.printStackTrace();

    }finally {

        if(httpConn!=null)httpConn.disconnect();

        if(baos!=null) try{baos.close();} catch (IOException e) {}

        if(is!=null) try {is.close();} catch (IOException e) {}

    }

    return body;

}

 

上面的重点为:在访问的时候为http头信息,也就是在request header里面添加一个名称为Authorization的信息,内容为Basic+空格+base64编码(用户名+:+密码),这样的结构。

其中将用户名和密码以冒号连接起来,然后进行base64编码,JDK中对于base64的编码方法,不同的JDK(6、7、8)有不同的方法,我上面的示意代码是采用的apache codec的库,这里只要是进行base64编码即可,采用哪个库都无所谓。

2.2. 通过Java获取用户JSON Web服务调用

示例代码:
/**
 *
获取指定用户信息
 * @param userId
 
* @return
 
*/

public static String queryUserInfo(String userId){
    //两种URL方式均可
    //方式一:
    //String url = "http://localhost:8080/api/jsonws/user/get-user-by-id/user-id/"+userId;
    //
方式二:
    String url = "http://localhost:8080/api/jsonws/user/get-user-by-id?userId="+userId;
    String userInfo = TestApi.httpGet(url);
    return userInfo;
}


public static void main(String[] args) {

    String result = null;

    System.out.println("======================获取的用户信息==================");

    result = TestApi.queryUserInfo("36639");

    System.out.println(result);

}
返回结果:
======================获取的用户信息==================
{"agreedToTermsOfUse":false,"comments":"","companyId":"20097","contactId":"36640","createDate":1590739789379,"defaultUser":false,"emailAddress":"[email protected]","emailAddressVerified":false,"externalReferenceCode":"","facebookId":"0","failedLoginAttempts":0,"firstName":"Joe","googleUserId":"","graceLoginCount":0,"greeting":"Joe T Bloggs,欢迎您!","jobTitle":"Tester","languageId":"zh_CN","lastFailedLoginDate":null,"lastLoginDate":null,"lastLoginIP":"","lastName":"Bloggs","ldapServerId":"-1","lockout":false,"lockoutDate":null,"loginDate":null,"loginIP":"","middleName":"T","modifiedDate":1590739789474,"mvccVersion":"1","openId":"","portraitId":"0","reminderQueryAnswer":"","reminderQueryQuestion":"","screenName":"test2","status":0,"timeZoneId":"UTC","userId":"36639","uuid":"32cdc4ec-3876-9f95-7ec7-8e19dd15c195"}
 

2.3. 通过Java添加用户JSON Web服务调用

示例代码:

/**

 * 创建用户

 * @param userInfo

 * @return

 */

public static String addUserInfo(Map<String,String> userInfo){

    String url = "http://localhost:8080/api/jsonws/user/add-user";

    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append(url).append("?");

    for (Map.Entry<String, String> entry : userInfo.entrySet()) {

        if(entry.getValue()!=null && !entry.getValue().equals("")){

            //有效参数处理

            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

        }else{

            //无效参数处理(要null为参数传递值,请在参数名称前加上破折号。这是一个例子:)

            stringBuilder.append("-").append(entry.getKey()).append("&");

        }

    }

    url = stringBuilder.substring(0, stringBuilder.length() - 1);

    System.out.println(url);

    String result = TestApi.httpGet(url);

    return result;

}


public static void main(String[] args) {
    String result = null;
    System.out.println("======================新增用户==================");
    Map<String, String> userInfoMap = new HashMap();
    userInfoMap.put("companyId", "20097");//社区实例ID
   
userInfoMap.put("autoPassword", "false");//是否自动生成密码
    userInfoMap.put("password1", "test");//密码
    userInfoMap.put("password2", "test");//重复密码与password1一致
    userInfoMap.put("autoScreenName", "false");//是否自动
    userInfoMap.put("screenName", "test3");
    userInfoMap.put("emailAddress", "test3@163.com");//邮件地址
    userInfoMap.put("facebookId", "0");//单点登录,facebookId,long类型必填
    userInfoMap.put("openId", "");//单点登录,openId
   
userInfoMap.put("locale", "zh_CN");//地区
    userInfoMap.put("firstName", "Joe");
    userInfoMap.put("middleName", "T");
    userInfoMap.put("lastName", "Bloggs");
    userInfoMap.put("prefixId", "0");//long类型必填
    userInfoMap.put("suffixId", "0");//long类型必填
    userInfoMap.put("male", "true");//性别,是否男生
    userInfoMap.put("birthdayYear", "1970");//生日,年
    userInfoMap.put("birthdayMonth", "1");//生日,月
    userInfoMap.put("birthdayDay", "1");//生日,日
    userInfoMap.put("jobTitle", "Tester");//工作职称
    userInfoMap.put("groupIds", "");//组织
    userInfoMap.put("organizationIds", "");//机构
    userInfoMap.put("userGroupIds", "");//用户组
    userInfoMap.put("roleIds", "20105");//角色
    userInfoMap.put("sendEmail", "false");//是否发送邮件
    result = TestApi.addUserInfo(userInfoMap);
    System.out.println(result);
}

返回结果:

======================新增用户==================

{"agreedToTermsOfUse":false,"comments":"","companyId":"20097","contactId":"36650","createDate":1590750745852,"defaultUser":false,"emailAddress":"[email protected]","emailAddressVerified":false,"externalReferenceCode":"","facebookId":"0","failedLoginAttempts":0,"firstName":"Joe","googleUserId":"","graceLoginCount":0,"greeting":"Joe T Bloggs,欢迎您!","jobTitle":"Tester","languageId":"zh_CN","lastFailedLoginDate":null,"lastLoginDate":null,"lastLoginIP":"","lastName":"Bloggs","ldapServerId":"-1","lockout":false,"lockoutDate":null,"loginDate":null,"loginIP":"","middleName":"T","modifiedDate":1590750746019,"mvccVersion":"1","openId":"","portraitId":"0","reminderQueryAnswer":"","reminderQueryQuestion":"","screenName":"test3","status":0,"timeZoneId":"UTC","userId":"36649","uuid":"d143a6c4-b738-a3ac-0c86-80d204ccc407"}

 

 

2.4. 参数类型说明

使用HTTP协议将参数值作为字符串发送。在调用匹配的Java服务方法之前,每个参数值都将从转换 String为其目标Java类型。Liferay使用第三方开源库将每个对象转换为其适当的通用类型。可以为某些类型添加或更改转换,但是我们仅介绍标准转换过程。

通用类型:

转换为通用类型(例如,longStringboolean)是简单的。日期可以毫秒为单位。语言环境可以作为语言环境名称(例如enen_US)传递。要传递数字数组,请发送以 String逗号分隔的数字(例如,String 4,8,15,16,23,42可以转换为long[]type)。

集合类型:

除了常见类型外,参数还可以是List或类型Map。要传递List参数,请发送JSON数组。要传递Map参数,请发送JSON对象。这些类型的转换分两个步骤执行:

  • 第1-JSON反序列化:将JSON数组转换为,List<String> 并将JSON对象转换为Map<String, String>。出于安全原因,禁止在JSON反序列化中实例化任何类型。
  • 步骤2-Generification:每个String的元件List和Map被转换到它的目标类型(在该方法签名中指定的参数的通用的Java类型)。仅当Java参数类型使用泛型时才执行此步骤。

例如,让我们考虑将String数组转换[en,fr]为List<Locale>Java方法参数类型的JSON Web服务参数:

  • 第1-JSON反序列化:将JSON数组反序列化为 List<String>包含String的en和fr。
  • 第2-生成:将每个String都转换为Locale(通用类型),从而产生List<Locale>Java参数类型。

 

2.5. 注意事项

在参数值为null时,请在参数名称前加上破折号。这是一个例子:

http://localhost:8080/api/jsonws/bookmarksfolder/add-folder/parent-folder-id/0/name/News/-description

这是使用URL查询参数代替URL路径参数的等效示例:

http://localhost:8080/api/jsonws/bookmarksfolder/add-folder?parentFolderId=0&name=News&-description

description参数被解释为null。尽管此参数在上面的URL中位于最后一个,但不一定要最后一个。

 

相关标签: liferay