极光推送工具类 java httpClient

来源:互联网 发布:汽车配件查询软件 编辑:程序博客网 时间:2024/06/04 22:47

极光推送工具类 java

使用  httpClient 调用


import java.io.IOException;import net.sf.json.JSONObject;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicHeader;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import sy.common.Constants;import com.alibaba.fastjson.JSONArray;/** * java后台极光推送 *  * <pre> * 使用 httpClient请求发送客户端 * </pre> */public class JiguangPushTool {private static final Logger log = LoggerFactory.getLogger(JiguangPushTool.class);private static String pushUrl = Constants.JIGUANGPUSH_pushUrl;private static String receivedURL = Constants.JIGUANGPUSH_receivedURL;/** APNs是否生产环境 ,默认为true */private static boolean apns_production = !Constants.JIGUANGPUSH_DevMode;/** * 离线消息保留时长(秒),默认 86400 (1 天) *  * <pre> * 推送当前用户不在线时,为该用户保留多长时间的离线消息,以便其上线时再次推送。 * 默认 86400 (1 天),最长 10 天。 * 设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到。 * </pre> */private static int time_to_live = 86400;/** * 极光推送 */@Testpublic void testJiguangPush() {String ALERT = "1分钟完成创建、支持语音图文直播、直播过程清晰无卡顿";String alias = "";// 声明别名try {String result = push(alias, ALERT, "1", "jw123456");System.out.println("result = " + result);if (StringUtil.isEmpty(result)) {return;}JSONObject resData = JSONObject.fromObject(result);if (resData.containsKey("error")) {log.info("别名为 [ " + alias + " ] 的信息推送失败!");JSONObject error = JSONObject.fromObject(resData.get("error"));log.info("信息为 " + error.get("message").toString());} else {log.info("别名为 [ " + alias + " ] 的信息推送成功!");}} catch (Exception e) {e.printStackTrace();log.error("别名为 [ " + alias + " ] 的信息推送失败!", e);}}/** * 推送方法 *  * @param alias *            别名 * @param alert *            消息内容 不超过2000个字节。使用 utf-8 编码,所以一个汉字占用 3 个字节长度。 * @param ypage *            跳转页面 * @param yparam *            跳转参数 */public static String push(String alias, String alert, String ypage, String yparam) {// byte[] aa=alias.getBytes("UTF-8");// if(aa.length>1800){//// }return push(alias, alert, ypage, yparam, apns_production, time_to_live);}/** * 推送方法 *  * @param alias *            别名 * @param alert *            消息内容 不超过2000个字节。使用 utf-8 编码,所以一个汉字占用 3 个字节长度。 * @param ypage *            消息类型 * @param yparam *            消息id * @param apns_production *            APNs是否生产环境 ,默认为true * @param time_to_live *            离线消息保留时长(秒),默认 86400 (1 天) */public static String push(String alias, String alert, String ypage, String yparam, boolean apns_production, int time_to_live) {String authorization = pickAuth();String data = generateJson(alias, alert, ypage, yparam, apns_production, time_to_live).toString();System.out.println("data=" + data);return sendPostRequest(pushUrl, data, authorization);}/** * 获取android、ios的消息的统计数据 *  * @param receivedURL * @return */public static String received(String receivedURL) {String authorization = pickAuth();String result = sendGetRequest(receivedURL, authorization);return result;}/** * 组装极光推送专用json串 *  * @param alias * @param alert * @param ypage *            消息类型 * @param yparam *            消息id * @param apns_production * @param time_to_live * @return */public static JSONObject generateJson(String alias, String alert, String ypage, String yparam, boolean apns_production, int time_to_live) {JSONObject json = new JSONObject();//JSONArray platform = new JSONArray();// 平台//platform.add("android");//platform.add("ios");JSONObject audience = new JSONObject();// 推送目标JSONArray alias1 = new JSONArray();alias1.add(alias);audience.put("alias", alias1);JSONObject notification = new JSONObject();// 通知内容JSONObject android = new JSONObject();// android通知内容android.put("alert", alert);android.put("builder_id", 1);JSONObject android_extras = new JSONObject();// android额外参数android_extras.put("ypage", ypage);android_extras.put("yparam", yparam);android.put("extras", android_extras);JSONObject ios = new JSONObject();// ios通知内容ios.put("alert", alert);ios.put("sound", "default");ios.put("badge", "+1");JSONObject ios_extras = new JSONObject();// ios额外参数ios_extras.put("ypage", ypage);ios_extras.put("yparam", yparam);ios.put("extras", ios_extras);notification.put("android", android);notification.put("ios", ios);JSONObject options = new JSONObject();// 设置参数options.put("time_to_live", Integer.valueOf(time_to_live));options.put("apns_production", apns_production);json.put("platform", "all");json.put("audience", audience);json.put("notification", notification);json.put("options", options);return json;}/** * 发送Post请求(json格式) *  * @param reqURL * @param data * @param authorization * @return result */public static String sendPostRequest(String reqURL, String data, String authorization) {HttpPost httpPost = new HttpPost(reqURL);CloseableHttpClient httpClient = HttpClients.createDefault();String result = "";CloseableHttpResponse response = null;try {httpPost.setHeader("Authorization", authorization);httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");StringEntity stringEntity = new StringEntity(data, "UTF-8");stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);response = httpClient.execute(httpPost);HttpEntity httpEntity = response.getEntity();if (httpEntity != null) {result = EntityUtils.toString(httpEntity, "UTF-8");EntityUtils.consume(httpEntity);}} catch (Exception e) {e.printStackTrace();log.error("请求通信[" + reqURL + "]时偶遇异常,堆栈轨迹如下", e);} finally {closeHttp(response, httpClient);}return result;}public static String sendGetRequest(String reqURL, String auth) {String result = null; // 响应内容CloseableHttpResponse response = null;CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建默认的httpClient实例try {HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGethttpGet.setHeader("Authorization", auth);httpGet.setHeader(HTTP.CONTENT_TYPE, "application/json");response = httpClient.execute(httpGet); // 执行GET请求HttpEntity httpEntity = response.getEntity(); // 获取响应实体if (null != httpEntity) {result = EntityUtils.toString(httpEntity, "UTF-8");EntityUtils.consume(httpEntity);}response.close();} catch (Exception e) {e.printStackTrace();log.error("异常信息:", e);} finally {closeHttp(response, httpClient);}return result;}private static void closeHttp(CloseableHttpResponse response, CloseableHttpClient httpClient) {try {if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}try {if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}public static String pickAuth() {String auth64 = Base64.getEncodeMsg(Constants.JIGUANGPUSH_APPKEY + ":" + Constants.JIGUANGPUSH_MASTERSECRET);String authorization = "Basic " + auth64;System.out.println("auth64=" + authorization);return authorization;}}


0 0
原创粉丝点击