极光IM JAVA后台对接

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

极光IM JAVA后台对接_第1张图片

 

 话不多说,贴代码

pom.xml

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



    
        wnews
        com.fd.wnews
        0.0.1-SNAPSHOT
    
    4.0.0

    fd-wnews-common
    
        
            org.springframework
            spring-context
        
        
            com.baomidou
            mybatis-plus-support
        
        
            io.swagger
            swagger-annotations
        
        
            io.netty
            netty-transport
        
        
            com.fd.businessengine
            be-common-entity
            1.0.2-SNAPSHOT
            compile
        


        
        
            cn.jpush.api
            jpush-client
            3.2.17
            compile
        
        
            org.apache.httpcomponents
            httpclient
        
        
            org.apache.httpcomponents
            httpmime
            4.5.9
        
        
            com.arronlong
            httpclientutil
            1.0.4
        

        
            cn.jpush.api
            jiguang-common
            1.1.3
        
        
            backport-util-concurrent
            backport-util-concurrent
            3.1
        

        
            cn.jpush.api
            jmessage-client
            1.1.8
        
    


用户实体类

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 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 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;

/**
 * 

* 系统参数配置表 服务实现类 *

* * @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 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 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验证要求

极光IM JAVA后台对接_第2张图片

 

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

极光IM JAVA后台对接_第3张图片

 极光IM JAVA后台对接_第4张图片

 

你可能感兴趣的:(java,第三方对接)