極光官網的對接文檔: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的字符串