极光IM JAVA后台对接

极光官网的对接文档:https://docs.jiguang.cn/jmessage/server/rest_api_im/

 

 话不多说,贴代码

pom.xml

以下包含了极光推送所需的依赖,这里为了方便全部复制了

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>wnews</artifactId>
        <groupId>com.fd.wnews</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>fd-wnews-common</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-support</artifactId>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-transport</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fd.businessengine</groupId>
            <artifactId>be-common-entity</artifactId>
            <version>1.0.2-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>


        <!--极光-->
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.2.17</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.9</version>
        </dependency>
        <dependency>
            <groupId>com.arronlong</groupId>
            <artifactId>httpclientutil</artifactId>
            <version>1.0.4</version>
        </dependency>

        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jiguang-common</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>backport-util-concurrent</groupId>
            <artifactId>backport-util-concurrent</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jmessage-client</artifactId>
            <version>1.1.8</version>
        </dependency>
    </dependencies>


</project>

用户实体类

package com.fd.wnews.entity;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.util.Objects;

/**
 * @Description 用户对象
 * @Author lc
 * @Date 2019-11-21 下午 4:59
 */
public class JiGuangUser implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "用户登录名")
    private String username;
    @ApiModelProperty(value = "登录密码")
    private String password;
    @ApiModelProperty(value = "用户所属于的应用的appkey")
    private String appkey;
    @ApiModelProperty(value = "用户昵称")
    private String nickname;
    @ApiModelProperty(value = "生日")
    private String birthday;
    @ApiModelProperty(value = "头像")
    private String avatar;
    @ApiModelProperty(value = "性别:0-未知/1-男/2-女")
    private String gender;
    @ApiModelProperty(value = "用户签名")
    private String signature;
    @ApiModelProperty(value = "用户所属地区")
    private String region;
    @ApiModelProperty(value = "用户详细地址")
    private String address;
    @ApiModelProperty(value = "用户创建时间")
    private String ctime;
    @ApiModelProperty(value = "用户最后修改时间")
    private String mtime;
    @ApiModelProperty(value = "用户自定义json对象")
    private String extras;

    @Override
    public String toString() {
        return "JiGuangUser{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", appkey='" + appkey + '\'' +
                ", nickname='" + nickname + '\'' +
                ", birthday='" + birthday + '\'' +
                ", avatar='" + avatar + '\'' +
                ", gender='" + gender + '\'' +
                ", signature='" + signature + '\'' +
                ", region='" + region + '\'' +
                ", address='" + address + '\'' +
                ", ctime='" + ctime + '\'' +
                ", mtime='" + mtime + '\'' +
                ", extras='" + extras + '\'' +
                '}';
    }
//    @Override
//    public String toString() {
//        return "[{" +
//                "username='" + username + '\'' +
//                ", password='" + password + '\'' +
//                ", appkey='" + appkey + '\'' +
//                ", nickname='" + nickname + '\'' +
//                ", birthday='" + birthday + '\'' +
//                ", avatar='" + avatar + '\'' +
//                ", gender='" + gender + '\'' +
//                ", signature='" + signature + '\'' +
//                ", region='" + region + '\'' +
//                ", address='" + address + '\'' +
//                ", ctime='" + ctime + '\'' +
//                ", mtime='" + mtime + '\'' +
//                ", extras='" + extras + '\'' +
//                '}'+']';
//    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        JiGuangUser that = (JiGuangUser) o;
        return Objects.equals(username, that.username) &&
                Objects.equals(password, that.password) &&
                Objects.equals(appkey, that.appkey) &&
                Objects.equals(nickname, that.nickname) &&
                Objects.equals(birthday, that.birthday) &&
                Objects.equals(avatar, that.avatar) &&
                Objects.equals(gender, that.gender) &&
                Objects.equals(signature, that.signature) &&
                Objects.equals(region, that.region) &&
                Objects.equals(address, that.address) &&
                Objects.equals(ctime, that.ctime) &&
                Objects.equals(mtime, that.mtime) &&
                Objects.equals(extras, that.extras);
    }

    @Override
    public int hashCode() {
        return Objects.hash(username, password, appkey, nickname, birthday, avatar, gender, signature, region, address, ctime, mtime, extras);
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAppkey() {
        return appkey;
    }

    public void setAppkey(String appkey) {
        this.appkey = appkey;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCtime() {
        return ctime;
    }

    public void setCtime(String ctime) {
        this.ctime = ctime;
    }

    public String getMtime() {
        return mtime;
    }

    public void setMtime(String mtime) {
        this.mtime = mtime;
    }

    public String getExtras() {
        return extras;
    }

    public void setExtras(String extras) {
        this.extras = extras;
    }
}

 

controller代码

package com.fd.wnews.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fd.businessengine.common.result.Result;
import com.fd.wnews.entity.JiGuangUser;
import com.fd.wnews.service.JiGuangPushService;
import com.fd.wnews.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 极光第三方推送
 * @Author lc
 * @Date 2019-11-21 下午 1:48
 */
@Api(tags = "极光第三方推送")
@RestController
@RequestMapping(value = "/jiGuang")
public class JiGuangPushController extends BaseFDController {

    @Autowired
    JiGuangPushService jiGuangPushService;

    /**
     * @param username  用户名称
     * @param password  用户密码
     * @param nickname  用户昵称
     * @param avatar    用户头像
     * @param birthday  用户生日
     * @param signature 签名
     * @param gender    性别
     * @param region    地区
     * @param address   地址
     * @param extras    用户自定义json对象
     * @return com.fd.businessengine.common.result.Result
     * @Description 用户注册
     * @Author lc
     * @Date 2019-11-21 下午 5:31
     **/
    @ApiOperation(value = "用户注册")
    @PostMapping(path = "/userRegister", name = "用户注册")
    public Result userRegister(
            @ApiParam(value = "用户名称")
            @RequestParam(name = "username", required = true) String username,

            @ApiParam(value = "用户密码")
            @RequestParam(name = "password", required = true) String password,

            @ApiParam(value = "用户昵称")
            @RequestParam(name = "nickname", required = false) String nickname,

            @ApiParam(value = "用户头像")
            @RequestParam(name = "avatar", required = false) String avatar,

            @ApiParam(value = "用户生日")
            @RequestParam(name = "birthday", required = false) String birthday,

            @ApiParam(value = "签名")
            @RequestParam(name = "signature", required = false) String signature,

            @ApiParam(value = "性别")
            @RequestParam(name = "gender", required = false) String gender,

            @ApiParam(value = "地区")
            @RequestParam(name = "region", required = false) String region,

            @ApiParam(value = "地址")
            @RequestParam(name = "address", required = false) String address,

            @ApiParam(value = "用户自定义json对象")
            @RequestParam(name = "extras", required = false) String extras
    ) {

        JiGuangUser jiGuangUser = new JiGuangUser();
        jiGuangUser.setUsername(username);
        jiGuangUser.setPassword(password);
        jiGuangUser.setNickname(nickname);
        jiGuangUser.setAvatar(avatar);
        jiGuangUser.setBirthday(birthday);
        jiGuangUser.setSignature(signature);
        jiGuangUser.setGender(gender);
        jiGuangUser.setRegion(region);
        jiGuangUser.setAddress(address);
        jiGuangUser.setExtras(extras);
        List<JiGuangUser> jiGuangUsers = new ArrayList<>();
        jiGuangUsers.add(jiGuangUser);
        String param = JSONArray.toJSON(jiGuangUsers).toString();
        String resultStr = jiGuangPushService.userRegister(param);
        return Result.success(resultStr);
    }

    /**
     * @param username  用户名称
     * @param nickname  用户昵称
     * @param avatar    用户头像
     * @param birthday  用户生日
     * @param signature 签名
     * @param gender    性别
     * @param region    地区
     * @param address   地址
     * @param extras    用户自定义json对象
     * @return com.fd.businessengine.common.result.Result
     * @Description 更新用户
     * @Author lc
     * @Date 2019-11-21 下午 5:31
     **/
    @ApiOperation(value = "更新用户")
    @PostMapping(path = "/updateUser", name = "更新用户")
    public Result updateUser(
            @ApiParam(value = "用户名称")
            @RequestParam(name = "username", required = true) String username,

            @ApiParam(value = "用户昵称")
            @RequestParam(name = "nickname", required = false) String nickname,

            @ApiParam(value = "用户头像")
            @RequestParam(name = "avatar", required = false) String avatar,

            @ApiParam(value = "用户生日")
            @RequestParam(name = "birthday", required = false) String birthday,

            @ApiParam(value = "签名")
            @RequestParam(name = "signature", required = false) String signature,

            @ApiParam(value = "性别")
            @RequestParam(name = "gender", required = false) String gender,

            @ApiParam(value = "地区")
            @RequestParam(name = "region", required = false) String region,

            @ApiParam(value = "地址")
            @RequestParam(name = "address", required = false) String address,

            @ApiParam(value = "用户自定义json对象")
            @RequestParam(name = "extras", required = false) String extras
    ) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", username);
        jsonObject.put("nickname", nickname);
        jsonObject.put("avatar", avatar);
        jsonObject.put("birthday", birthday);
        jsonObject.put("signature", signature);
        jsonObject.put("gender", gender);
        jsonObject.put("region", region);
        jsonObject.put("address", address);
        jsonObject.put("extras", extras);
        String resultStr = jiGuangPushService.updateUser(jsonObject.toString(), username);
        return Result.success(resultStr);
    }

    /**
     * @param username 用户名称
     * @return com.fd.businessengine.common.result.Result
     * @Description 获取用户详情
     * @Author lc
     * @Date 2019-11-22 上午 10:14
     **/
    @ApiOperation(value = "获取用户详情")
    @GetMapping(path = "/getUserByName", name = "获取用户详情")
    public Result getUserByName(
            @ApiParam(value = "用户名称")
            @RequestParam(name = "username", required = true) String username
    ) {
        String resultStr = jiGuangPushService.getUserByName(username);
        return Result.success(resultStr);
    }


    /**
     * @param owner_username   群主名称
     * @param name             群组名称
     * @param members_username 成员名称
     * @param avatar           群组头像
     * @param desc             描述
     * @param flag             类型(1-私有群/2-公开群)
     * @return com.fd.businessengine.common.result.Result
     * @Description
     * @Author lc
     * @Date 2019-11-22 上午 9:18
     **/
    @ApiOperation(value = "创建群组")
    @PostMapping(path = "/createGroups", name = "创建群组")
    public Result createGroups(
            @ApiParam(value = "群主名称")
            @RequestParam(name = "owner_username", required = true) String owner_username,

            @ApiParam(value = "群组名称")
            @RequestParam(name = "name", required = true) String name,

            @ApiParam(value = "成员名称")
            @RequestParam(name = "members_username", required = true) String[] members_username,

            @ApiParam(value = "群组头像")
            @RequestParam(name = "avatar", required = false) String avatar,

            @ApiParam(value = "描述")
            @RequestParam(name = "desc", required = false) String desc,

            @ApiParam(value = "类型(1-私有群/2-公开群)")
            @RequestParam(name = "flag", defaultValue = "1", required = false) Integer flag
    ) {

        JSONObject jsonObject = new JSONObject();
        System.out.println(members_username);
        jsonObject.put("owner_username", owner_username);
        jsonObject.put("name", name);
        jsonObject.put("members_username", members_username);
        jsonObject.put("avatar", avatar);
        jsonObject.put("flag", flag);
        jsonObject.put("desc", desc);
        jsonObject.put("MaxMemberCount", 500);
        String resultStr = jiGuangPushService.createGroups(jsonObject.toString());
        return Result.success(resultStr);
    }


    /**
     * @param gid 群组ID
     * @return com.fd.businessengine.common.result.Result
     * @Description 获取群组详情
     * @Author lc
     * @Date 2019-11-22 下午 3:02
     **/
    @ApiOperation(value = "获取群组详情")
    @GetMapping(path = "/getGroupItem", name = "获取群组详情")
    public Result getGroupItem(
            @ApiParam(value = "群组ID")
            @RequestParam(name = "gid", required = true) String gid
    ) {
        String resultStr = jiGuangPushService.getGroupItem(gid);
        return Result.success(resultStr);
    }


    /**
     * @param file 文件
     * @param type 类型
     * @return com.fd.businessengine.common.result.Result
     * @Description 文件上传
     * @Author lc
     * @Date 2019-11-22 下午 4:20
     **/
    @ApiOperation(value = "文件上传")
    @PostMapping(path = "/fileUpload", name = "文件上传")
    public Result fileUpload(
            @ApiParam(value = "文件名称")
            @RequestParam(name = "filename", required = true) MultipartFile file,

            @ApiParam(value = "文件类型,支持image,file,voice")
            @RequestParam(name = "type", required = true) String type
    ) {
        String filePath = "";
        if (!file.isEmpty()) {
            String tmpdir = System.getProperty("java.io.tmpdir");
            File tmpFile = new File(tmpdir, UUIDUtil.getUUID() + "." + file.getOriginalFilename().split("\\.")[1]);
            try {
                file.transferTo(tmpFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            filePath = tmpFile.getAbsolutePath();
        }
        //参数获取
        String resultStr = jiGuangPushService.fileUpload(filePath, type);
        return Result.success(resultStr);
    }

    /**
     * @param mediaId 图片mediaId
     * @return com.fd.businessengine.common.result.Result
     * @Description 文件下载
     * @Author lc
     * @Date 2019-11-22 下午 3:40
     **/
    @ApiOperation(value = "文件下载")
    @GetMapping(path = "/fileDownload", name = "文件下载")
    public Result fileDownload(
            @ApiParam(value = "图片mediaId")
            @RequestParam(name = "mediaId", required = false) String mediaId
    ) {
        String resultStr = jiGuangPushService.fileDownload(mediaId);
        return Result.success(resultStr);
    }

}

 service代码

package com.fd.wnews.service;

import cn.jpush.api.push.PushResult;

import java.util.Map;

/**
 * @Description 极光消息推送
 * @Author lc
 * @Date 2019-11-20 上午 10:59
 */
public interface JiGuangPushService {

    /**
     * @param param
     * @return cn.jpush.api.push.PushResult
     * @Description 极光消息推送
     * @Author lc
     * @Date 2019-11-22 上午 10:15
     **/
    PushResult messagePush(Map<String, String> param);

    /**
     * @param param json字符串
     * @return java.lang.String
     * @Description 用户注册信息推送
     * @Author lc
     * @Date 2019-11-22 上午 9:27
     **/
    String userRegister(String param);

    /**
     * @param username 用户名称
     * @return java.lang.String
     * @Description 获取用户详情
     * @Author lc
     * @Date 2019-11-22 上午 10:01
     **/
    String getUserByName(String username);

    /**
     * @param param    json字符串
     * @param userName 用户名称
     * @return java.lang.String
     * @Description 更新用户
     * @Author lc
     * @Date 2019-11-22 上午 10:44
     **/
    String updateUser(String param, String userName);

    /**
     * @param param json字符串
     * @return java.lang.String
     * @Description 创建群聊
     * @Author lc
     * @Date 2019-11-22 下午 2:55
     **/
    String createGroups(String param);


    /**
     * @param gid 群组ID
     * @return java.lang.String
     * @Description 获取群组详情
     * @Author lc
     * @Date 2019-11-22 下午 3:03
     **/
    String getGroupItem(String gid);

    /**
     * @param filePath 文件路径
     * @param fileType 文件类型
     * @return java.lang.String
     * @Description 文件上传
     * @Author lc
     * @Date 2019-11-22 下午 4:21
     **/
    String fileUpload(String filePath, String fileType);

    /**
     * @param mediaId 图片mediaId
     * @return com.fd.businessengine.common.result.Result
     * @Description 文件下载
     * @Author lc
     * @Date 2019-11-22 下午 3:40
     **/
    String fileDownload(String mediaId);
} 

 service实现类代码

package com.fd.wnews.service.impl;

import cn.jpush.api.push.PushResult;
import com.fd.wnews.log.LogUtil;
import com.fd.wnews.service.JiGuangPushService;
import com.fd.wnews.utils.jiguang.PushUtil;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 系统参数配置表 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-10-22
 */
@Service
public class JiGuangPushServiceImpl implements JiGuangPushService {

    private static final PoolingHttpClientConnectionManager connPool;

    static {
        connPool = new PoolingHttpClientConnectionManager();
        // Increase max total connection to 200
        connPool.setMaxTotal(200);//configurable through app.properties
        // Increase default max connection per route to 50
        connPool.setDefaultMaxPerRoute(20);//configurable through app.properties
    }


    /**
     * @param param
     * @return cn.jpush.api.push.PushResult
     * @Description 极光消息推送
     * @Author lc
     * @Date 2019-11-20 上午 11:38
     **/
    @Override
    public PushResult messagePush(Map<String, String> param) {
        return PushUtil.jpushAll(param);
    }


    /**
     * @param param json字符串
     * @return java.lang.String
     * @Description 用户注册信息推送
     * @Author lc
     * @Date 2019-11-22 上午 9:28
     **/
    @Override
    public String userRegister(String param) {
        String url = "https://api.im.jpush.cn/v1/users/";
        String resultStar = pushPost(param, url, "post");
        return resultStar;
    }

    /**
     * @param username 根据用户名称获取用户
     * @return java.lang.String
     * @Description 获取用户
     * @Author lc
     * @Date 2019-11-22 上午 10:13
     **/
    @Override
    public String getUserByName(String username) {
        String url = "https://api.im.jpush.cn/v1/users/" + username;
        String resultStar = pushGet("", url);
        return resultStar;
    }


    @Override
    public String updateUser(String param, String userName) {
        String url = "https://api.im.jpush.cn/v1/users/" + userName;
        String resultStar = pushPost(param, url, "put");
        return resultStar;
    }

    /**
     * @param param json字符串
     * @return java.lang.String
     * @Description 创建群聊信息推送
     * @Author lc
     * @Date 2019-11-22 上午 9:29
     **/
    @Override
    public String createGroups(String param) {
//        return PushUtil.createGroups(param);
        String url = "https://api.im.jpush.cn/v1/groups/";
        String resultStar = pushPost(param, url, "post");
        return resultStar;
    }


    /**
     * @param gid 群组ID
     * @return java.lang.String
     * @Description 获取群组详情
     * @Author lc
     * @Date 2019-11-22 下午 3:04
     **/
    @Override
    public String getGroupItem(String gid) {
        String url = "https://api.im.jpush.cn/v1/groups/" + gid;
        String resultStar = pushGet("", url);
        return resultStar;
    }

    /**
     * @param filePath 文件路径
     * @param fileType 文件类型
     * @return java.lang.String
     * @Description 文件上传
     * @Author lc
     * @Date 2019-11-22 下午 4:21
     **/
    @Override
    public String fileUpload(String filePath, String fileType) {
        return PushUtil.uploadFile(filePath, fileType);
    }

    /**
     * @param mediaId 图片mediaId
     * @return java.lang.String
     * @Description 图片下载
     * @Author lc
     * @Date 2019-11-22 下午 3:42
     **/
    @Override
    public String fileDownload(String mediaId) {
        String url = "https://api.im.jpush.cn/v1/resource?mediaId=" + mediaId;
        String resultStar = pushGet("", url);
        return resultStar;
    }

    /**
     * @param param 参数
     * @param url   调用地址
     * @return java.lang.String
     * @Description post方式推送
     * @Author lc
     * @Date 2019-11-22 上午 9:31
     **/
    private String pushPost(String param, String url, String mothodType) {
        String resultStar = "";
        try {
            String authorization = PushUtil.getAuthorization();
            resultStar = PushUtil.post(url, authorization, param, connPool, mothodType);
        } catch (Exception e) {
            LogUtil.error("信息推送失败:" + e);
            e.printStackTrace();
        }
        return resultStar;
    }

    /**
     * @param param 参数
     * @param url   调用地址
     * @return java.lang.String
     * @Description get方式
     * @Author lc
     * @Date 2019-11-22 上午 9:31
     **/
    private String pushGet(String param, String url) {
        String resultStar = "";
        try {
            String authorization = PushUtil.getAuthorization();
            System.out.println(authorization);
            resultStar = PushUtil.get(url, authorization, param, connPool);
        } catch (Exception e) {
            LogUtil.error("获取失败:" + e);
            e.printStackTrace();
        }
        return resultStar;
    }


}

 工具类代码(注意,调用极光第三方的接口下面有两种方式,一种是使用http接口调用,另一种极光也提供了内置的方法,如下面的文件上传的方法,除了文件上传其他的接口都是使用http的方式调用)

package com.fd.wnews.utils.jiguang;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.group.CreateGroupResult;
import cn.jmessage.api.resource.ResourceClient;
import cn.jmessage.api.resource.UploadResult;
import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import sun.misc.BASE64Encoder;

import static com.fd.wnews.utils.jiguang.ClientExample.LOG;

/**
 * @Description 极光推送工具类
 * @Author lc
 * @Date 2019-11-20 上午 11:20
 */
public class PushUtil {

    public static final String APP_KEY = "************";
    public static final String MASTER_SECRET = "************";

    /**
     * @param url             请求地址
     * @param authorization   认证参数
     * @param pushParmJsonStr 参数
     * @param connPool        连接池
     * @return java.lang.String
     * @Description 参数推送POST请求
     * @Author lc
     * @Date 2019-11-21 下午 5:56
     **/
    public static String post(String url, String authorization, String pushParmJsonStr, PoolingHttpClientConnectionManager connPool, String mothodType) {
        String returnJson = null;
        Header[] headers = HttpHeader.custom()
                .other("Authorization", authorization.trim())
                .userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36").build();
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setConnectionManager(connPool).build();

            HttpConfig config = HttpConfig.custom()
                    .headers(headers)    //设置headers,不需要时则无需设置
                    .url(url)              //设置请求的url
                    .json(pushParmJsonStr)              //设置请求参数,没有则无需设置
                    .encoding("utf-8") //设置请求和返回编码,默认就是Charset.defaultCharset()
                    .client(client)    //如果只是简单使用,无需设置,会自动获取默认的一个client对象
                    .inenc("utf-8")  //设置请求编码,如果请求返回一直,不需要再单独设置
                    .inenc("utf-8");    //设置返回编码,如果请求返回一直,不需要再单独设置
            if (StringUtils.equals(mothodType, "post")) {
                returnJson = HttpClientUtil.post(config);//post请求
            } else if (StringUtils.equals(mothodType, "put")) {
                returnJson = HttpClientUtil.put(config);//post请求
            }
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        return returnJson;
    }


    /**
     * @param url             请求地址
     * @param authorization   认证参数
     * @param pushParmJsonStr 参数
     * @param connPool        连接池
     * @return java.lang.String
     * @Description 参数推送GET请求
     * @Author lc
     * @Date 2019-11-21 下午 5:56
     **/
    public static String get(String url, String authorization, String pushParmJsonStr, PoolingHttpClientConnectionManager connPool) {
        String returnJson = null;
        Header[] headers = HttpHeader.custom()
                .other("Authorization", authorization.trim())
                .userAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36").build();
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setConnectionManager(connPool).build();

            HttpConfig config = HttpConfig.custom()
                    .headers(headers)    //设置headers,不需要时则无需设置
                    .url(url)              //设置请求的url
                    .json(pushParmJsonStr)              //设置请求参数,没有则无需设置
                    .encoding("utf-8") //设置请求和返回编码,默认就是Charset.defaultCharset()
                    .client(client)    //如果只是简单使用,无需设置,会自动获取默认的一个client对象
                    .inenc("utf-8")  //设置请求编码,如果请求返回一直,不需要再单独设置
                    .inenc("utf-8");    //设置返回编码,如果请求返回一直,不需要再单独设置
            returnJson = HttpClientUtil.get(config);//post请求
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        return returnJson;
    }

    /**
     * @param jsonObject
     * @return java.lang.String
     * @Description 创建群聊 (可以使用http请求,也可以使用极光内置的接口调用)
     * 特别注意:参数owner_username 群主名称和 members_username 群成员名称 一定要调用注册接口注册过的
     * @Author lc
     * @Date 2019-11-22 下午 2:57
     **/
    public static String createGroups(JSONObject jsonObject) {
        JMessageClient client = new JMessageClient(APP_KEY, MASTER_SECRET);
        CreateGroupResult res = null;
        try {
            String owner_username = jsonObject.getString("owner_username");
            String name = jsonObject.getString("name");
            String members_username = jsonObject.getString("members_username");
            System.out.println(members_username);
            String avatar = jsonObject.getString("avatar");
            Integer flag = jsonObject.getInteger("flag");
            String desc = jsonObject.getString("desc");
            res = client.createGroup(owner_username, name, desc, avatar, flag, members_username);
            LOG.info(res.getName());
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Message: " + e.getMessage());
        }
        return res.getName();
    }

    /**
     * 文件上传
     *
     * @param filePath
     * @param fileType
     * @return
     */
    public static String uploadFile(String filePath, String fileType) {
        ResourceClient client = new ResourceClient(APP_KEY, MASTER_SECRET);
        String mediaId = "";
        try {
            UploadResult result = client.uploadFile(filePath, fileType);
            mediaId = result.getMediaId();
            System.out.println(mediaId);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Message: " + e.getMessage());
        }
        return mediaId;
    }

    /**
     * @param str
     * @return java.lang.String
     * @Description BASE64加密方法
     * @Author lc
     * @Date 2019-11-21 下午 3:29
     **/
    public static String encryptBASE64(String str) {
        byte[] key = str.getBytes();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String strs = base64Encoder.encodeBuffer(key);
        return strs;
    }


    /**
     * @return java.lang.String
     * @Description 验证采用 HTTP Basic 机制,即 HTTP Header(头)里加一个字段(Key/Value对):
     * Authorization: Basic base64_auth_string 其中 base64_auth_string 的生成算法为:base64(appKey:masterSecret)
     * 即,对 appKey 加上冒号,加上 masterSecret 拼装起来的字符串,再做 base64 转换
     * @Author lc
     * @Date 2019-11-21 下午 3:28
     **/
    public static String getAuthorization() {
        String base64_auth_string = encryptBASE64(APP_KEY + ":" + MASTER_SECRET);
        String authorization = "Basic " + base64_auth_string;
        return authorization;
    }


    public static void main(String[] args) {

        System.out.println(getAuthorization());


//        List<JiGuangUser> jiGuangUsers = new ArrayList<>();
//        JiGuangUser jiGuangUser = new JiGuangUser();
//        jiGuangUser.setUsername("liucong");
//        jiGuangUser.setPassword("123456");
//        jiGuangUsers.add(jiGuangUser);
//
//        System.out.println(JSONArray.toJSON(jiGuangUsers).toString());


    }


}

注意:controller中的接口所返回的Result对象可自行自定义,这里就不贴代码了

 

特别强调的是要注意调用的时候需要满足极光的http验证要求

 

比如使用postman直接调用需要使用  生成base64的字符串

 

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
极光推送是一款用于实现消息推送的云服务平台,它提供了丰富的消息推送功能。在Java后台中整合极光推送可以通过以下几个步骤来实现: 1. 注册极光推送账号并创建应用:首先,你需要在极光推送官网注册账号,并创建一个应用。在创建应用的过程中,会生成一个AppKey和一个Master Secret,这对应用进行身份验证非常重要。 2. 导入极光推送SDK:在你的Java项目中,你需要导入极光推送的Java SDK。你可以在极光推送官网上下载SDK,并将其添加到你的项目中。 3. 配置AppKey和Master Secret:在你的项目中找到配置文件(比如.properties文件),将AppKey和Master Secret配置到文件中。这些配置信息将用于与极光推送服务器进行身份验证。 4. 初始化JPushClient对象:在你的代码中,通过使用AppKey和Master Secret初始化一个JPushClient对象。这个对象将用于与极光推送服务器进行通信。 5. 构建推送消息:使用JPushClient对象,你可以构建不同类型的推送消息,比如通知、自定义消息等。根据你的需求,设置相应的参数,比如目标平台、接收者、通知内容等。 6. 发送推送消息:调用JPushClient对象的sendPush方法,将构建好的推送消息发送给极光推送服务器。服务器会根据你的设置,将消息推送给相应的设备。 以上就是极光推送Java后台整合的基本步骤。你可以根据自己的需求,进一步深入学习和使用极光推送的其他功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值