APP訊息推送 極光推送 示例程式碼

閒走天涯發表於2020-11-25

APP訊息推送 極光推送 示例程式碼


APP 進行別名繫結,以下介面進行 訊息推送

個推訊息推送程式碼示例連結https://blog.csdn.net/qq_36992948/article/details/110129625

/**
 * 描述:
 *
 * @author 閒走天涯
 * @create 2020/11/6 16:59
 */
@Slf4j
@RestController
@RequestMapping("/jpushNew")
public class JPushNewController {

    @Value("${jpush.token:}")
    private String jpush_token;
    @Value("${jpush.pushUrl:}")
    private String jpush_url;//推送介面
    @Value("${jpush.android.intent:}")
    private String intent;//android 指定跳轉頁面intent
    @Value("${jpush.send.content:}")
    private String content;//訊息內容 預設標題為APP

    /**
     * APP傳送極光訊息通知
     * @param alias 別名
     * @return
     */
    @RequestMapping("/appJpush")
    public JSONObject app_jpush(String alias){
        String data = "{\"platform\":\"all\",\"audience\":{\"alias\":[\""+alias+"\"]},\"notification\":{\"alert\":\""+content+"\",\"android\":{\"intent\":\""+intent+"\"},\"ios\":{\"sound\":\"sound.caf\"}}";
        return httpConnect_jpush(jpush_url,data);
    }

    /**
     *  極光推送 rest api
     * @param data
     * @return
     */
    public JSONObject httpConnect_jpush(String connectUrl, String data){
        JSONObject jsonObject = new JSONObject();
        log.info("【app極光推送】引數:data={},connectUrl={}",data,connectUrl);
        HttpsURLConnection conn = null;
        try{
            URL url = new URL(connectUrl);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Authorization","Basic " + jpush_token);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
            conn.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");

            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.write(data.getBytes());
            wr.flush();
            wr.close();
            int responseCode = conn.getResponseCode();
            InputStream is;

            if (responseCode >= 400){is = conn.getErrorStream();}
            else{ is = conn.getInputStream();}
            String result = new BufferedReader(new InputStreamReader(is))
                    .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
            jsonObject = JSONObject.parseObject(result);
            jsonObject.put("responseCode",responseCode);
            log.info("【app極光推送】結果result={}",jsonObject);
        }catch (Exception e){
            log.error("【app極光推送】異常",e);
            jsonObject.put("responseCode","500");
        }finally {
            if(conn!=null){
                conn.disconnect();
            }
        }
        return jsonObject;
    }
}

相關文章