本文目錄一覽:
- 1、jpush推送java後台怎麼調用
- 2、JAVA,當某個json數據中一個字段與另一個json數據中的字段值相同時,對兩個json進行合併且相加,
- 3、java JsonObject怎麼判斷一個json串中是否含有某個key值啊,
jpush推送java後台怎麼調用
原創作品,可以轉載,但是請標註出處地址
Java後台實現極光推送有兩種方式,一種是使用極光推送官方提供的推送請求API:,另一種則是使用官方提供的第三方Java SDK,這裡先進行第一種方式推送的實現代碼:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;
/**
* java後台極光推送方式一:使用Http API
* 此種方式需要自定義http請求發送客戶端:HttpClient
*/
@SuppressWarnings({ “deprecation”, “restriction” })
public class JiguangPush {
private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
private String masterSecret = “xxxxxxxxxxxxxxxxxxxx”;
private String appKey = “xxxxxxxxxxxxxxxxxxx”;
private String pushUrl = “”;
private boolean apns_production = true;
private int time_to_live = 86400;
private static final String ALERT = “推送信息”;
/**
* 極光推送
*/
public void jiguangPush(){
String alias = “123456”;//聲明別名
try{
String result = push(pushUrl,alias,ALERT,appKey,masterSecret,apns_production,time_to_live);
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());
}
log.info(“針對別名為” + alias + “的信息推送成功!”);
}catch(Exception e){
log.error(“針對別名為” + alias + “的信息推送失敗!”,e);
}
}
/**
* 組裝極光推送專用json串
* @param alias
* @param alert
* @return json
*/
public static JSONObject generateJson(String alias,String alert,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(“type”, “infomation”);
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(“type”, “infomation”);
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”, platform);
json.put(“audience”, audience);
json.put(“notification”, notification);
json.put(“options”, options);
return json;
}
/**
* 推送方法-調用極光API
* @param reqUrl
* @param alias
* @param alert
* @return result
*/
public static String push(String reqUrl,String alias,String alert,String appKey,String masterSecret,boolean apns_production,int time_to_live){
String base64_auth_string = encryptBASE64(appKey + “:” + masterSecret);
String authorization = “Basic ” + base64_auth_string;
return sendPostRequest(reqUrl,generateJson(alias,alert,apns_production,time_to_live).toString(),”UTF-8″,authorization);
}
/**
* 發送Post請求(json格式)
* @param reqURL
* @param data
* @param encodeCharset
* @param authorization
* @return result
*/
@SuppressWarnings({ “resource” })
public static String sendPostRequest(String reqURL, String data, String encodeCharset,String authorization){
HttpPost httpPost = new HttpPost(reqURL);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String result = “”;
try {
StringEntity entity = new StringEntity(data, encodeCharset);
entity.setContentType(“application/json”);
httpPost.setEntity(entity);
httpPost.setHeader(“Authorization”,authorization.trim());
response = client.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), encodeCharset);
} catch (Exception e) {
log.error(“請求通信[” + reqURL + “]時偶遇異常,堆棧軌跡如下”, e);
}finally{
client.getConnectionManager().shutdown();
}
return result;
}
/**
* BASE64加密工具
*/
public static String encryptBASE64(String str) {
byte[] key = str.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
String strs = base64Encoder.encodeBuffer(key);
return strs;
}
}
以上代碼中使用的是第一種方式實現推送,下面介紹第二種方式:使用java SDK
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
/**
* java後台極光推送方式二:使用Java SDK
*/
@SuppressWarnings({ “deprecation”, “restriction” })
public class JiguangPush {
private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
private static String masterSecret = “xxxxxxxxxxxxxxxxx”;
private static String appKey = “xxxxxxxxxxxxxxxx”;
private static final String ALERT = “推送信息”;
/**
* 極光推送
*/
public void jiguangPush(){
String alias = “123456”;//聲明別名
log.info(“對別名” + alias + “的用戶推送信息”);
PushResult result = push(String.valueOf(alias),ALERT);
if(result != null result.isResultOK()){
log.info(“針對別名” + alias + “的信息推送成功!”);
}else{
log.info(“針對別名” + alias + “的信息推送失敗!”);
}
}
/**
* 生成極光推送對象PushPayload(採用java SDK)
* @param alias
* @param alert
* @return PushPayload
*/
public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert){
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.alias(alias))
.setNotification(Notification.newBuilder()
.addPlatformNotification(AndroidNotification.newBuilder()
.addExtra(“type”, “infomation”)
.setAlert(alert)
.build())
.addPlatformNotification(IosNotification.newBuilder()
.addExtra(“type”, “infomation”)
.setAlert(alert)
.build())
.build())
.setOptions(Options.newBuilder()
.setApnsProduction(false)//true-推送生產環境 false-推送開發環境(測試使用參數)
.setTimeToLive(90)//消息在JPush服務器的失效時間(測試使用參數)
.build())
.build();
}
/**
* 極光推送方法(採用java SDK)
* @param alias
* @param alert
* @return PushResult
*/
public static PushResult push(String alias,String alert){
ClientConfig clientConfig = ClientConfig.getInstance();
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alert);
try {
return jpushClient.sendPush(payload);
} catch (APIConnectionException e) {
log.error(“Connection error. Should retry later. “, e);
return null;
} 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 Code: ” + e.getErrorCode());
log.info(“Error Message: ” + e.getErrorMessage());
log.info(“Msg ID: ” + e.getMsgId());
return null;
}
}
}
可以看出使用Java SDK實現推送的方式很簡單,代碼量也少,理解起來也不難,官方提供的SDK中講很多內容都實現了,我們只是需要配置一下信息,然後發起推送即可。需要注意的是使用第二種方式,需要導入極光官網提供的jar包。
直接在maven中的pom文件中加入:
dependency
groupIdcn.jpush.api/groupId
artifactIdjpush-client/artifactId
version3.2.15/version
/dependency
注意:在這裡極有可能會出現jar包衝突:具體哪個包我也忘記了,好像是個日誌包,你找到後刪除即可。
原本我們項目中也是採用第二種方式實現的,但是最後在提交代碼時發現一個問題,那就是雖然我們只是帶入了官網提供的那三個jar包,但是最後一統計,竟然無緣無故增多了80+個jar包,如此多的jar包提交過於臃腫,而且不現實,所以才臨時改變方案,採用第一種方式進行編碼。
代碼中採用的是別名方式進行推送,需要在在手機APP端進行別名設置,最好就是在用戶登錄之後就設置好,這樣只要用戶登錄一次,它的綁定別名就可以保存到極光服務器,而我們推送時,指定這個別名,就能將信息推送到對應用戶的手機上。
其實我們發起推送請求,只是將信息發送到了極光服務器之上,這個信息有一個保存時限,默認一天,只要用戶登錄手機APP,極光服務器就會將信息自動推送到對應別名的手機上,由此可見,信息並非由我們後天直接推送到手機,而是通過極光服務器這個中轉站,而這正式極光的工作。
注意:這裡告知一個技巧,這個別名設置的時候,其實直接將用戶ID設置為別名即可,既方便,又安全,不用再去想辦法生成一個唯一的串來進行標識,甚至需要在後台數據庫中用戶表中新增字段。
JAVA,當某個json數據中一個字段與另一個json數據中的字段值相同時,對兩個json進行合併且相加,
要判斷json數據的字段與其他數據是否相同,那麼肯定是要先解析json數據。解析json數據的方式很多,Gson、FastJson都是很簡便實用的工具。這裡以Gson為例。
import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Divination {
public static void main(String[] args) {
String jsonStr = “[{\”depid\”:\”5\”,\”score\”:\”10\”},{\”depid\”:\”4\”,\”score\”:\”40\”},{\”depid\”:\”4\”,\”score\”:\”30\”},{\”depid\”:\”5\”,\”score\”:\”30\”}]”;
System.out.println(“原始的json字符串:” + jsonStr);
// 解析
Gson gson = new Gson();
Type type = new TypeTokenArrayListJsonData() {
}.getType();
ArrayListJsonData list = gson.fromJson(jsonStr, type);
// 合併
ListJsonData ordered = new ArrayList();
MapInteger, JsonData map = new HashMap();
for (JsonData jsonData : list) {
JsonData data = map.get(jsonData.getDepid());
if (data != null) { // depid相同的合併score字段
data.setScore(data.getScore() + jsonData.getScore());
} else {
map.put(jsonData.getDepid(), jsonData);
ordered.add(jsonData);
}
}
// 還原為json字符串
System.out.println(“合併後json字符串:” + gson.toJson(map.values()));
System.out.println(“合併後json字符串(按原來的順序):” + gson.toJson(ordered));
}
}
class JsonData {
private int depid;
private int score;
public int getDepid() {
return depid;
}
public void setDepid(int depid) {
this.depid = depid;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
以上代碼中ListJsonData ordered = new ArrayList();是為了按原json數組的順序輸出合併後的結果,如果對順序無要求可以刪除相關代碼。
運行結果:
java JsonObject怎麼判斷一個json串中是否含有某個key值啊,
if (key in jsonObject) {
alert(‘有’);
} else {
沒有
}
看錯,原來是JAVA,上面是javascript的做法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/240932.html