Phonegap 极光推送api 服务器端推送代码
生活随笔
收集整理的這篇文章主要介紹了
Phonegap 极光推送api 服务器端推送代码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
.net 版本 極光推送 后臺接口
HttpWebResponseUtility類
using System; using System.Collections.Generic; using System.Text; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using System.IO.Compression; using System.Text.RegularExpressions;/// <summary> /// HttpWebResponseUtility 的摘要說明 /// </summary> public class HttpWebResponseUtility {/// <summary> /// 創(chuàng)建POST方式的HTTP請求 /// </summary> /// <param name="url">請求的URL</param> /// <param name="parameters">隨同請求POST的參數(shù)名稱及參數(shù)值字典</param> /// <param name="timeout">請求的超時時間</param> /// <param name="userAgent">請求的客戶端瀏覽器信息,可以為空</param> /// <param name="requestEncoding">發(fā)送HTTP請求時所用的編碼</param> /// <param name="cookies">隨同HTTP請求發(fā)送的Cookie信息,如果不需要身份驗證可以為空</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies){if (string.IsNullOrEmpty(url)){throw new ArgumentNullException("url");}if (requestEncoding == null){throw new ArgumentNullException("requestEncoding");}HttpWebRequest request = null;//如果是發(fā)送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)){ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);request = WebRequest.Create(url) as HttpWebRequest;request.ProtocolVersion = HttpVersion.Version10;}else{request = WebRequest.Create(url) as HttpWebRequest;}request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";//如果需要POST數(shù)據(jù) if (!(parameters == null || parameters.Count == 0)){StringBuilder buffer = new StringBuilder();int i = 0;foreach (string key in parameters.Keys){if (i > 0){buffer.AppendFormat("&{0}={1}", key, parameters[key]);}else{buffer.AppendFormat("{0}={1}", key, parameters[key]);}i++;}byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());using (Stream stream = request.GetRequestStream()){stream.Write(data, 0, data.Length);}}return request.GetResponse() as HttpWebResponse;}private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors){return true; //總是接受 } } View Codewebservice類
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient; using System.Data; using Newtonsoft.Json; using System.Web.Script.Serialization; using System.Net; using System.IO; using System.Text; using System.IO.Compression;/// <summary> ///WebService 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //若要允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù),請取消對下行的注釋。 [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {public WebService () {//如果使用設(shè)計的組件,請取消注釋以下行 //InitializeComponent(); }[WebMethod]public string HelloWorld() {return "Hello World";}public static string MD5Encrypt(string strSource){return MD5Encrypt(strSource, 32);}/// <summary> /// </summary> /// <param name="strSource">待加密字串</param> /// <param name="length">16或32值之一,其它則采用.net默認(rèn)MD5加密算法</param> /// <returns>加密后的字串</returns> public static string MD5Encrypt(string strSource, int length){byte[] bytes = Encoding.ASCII.GetBytes(strSource);byte[] hashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);StringBuilder sb = new StringBuilder();switch (length){case 16:for (int i = 4; i < 12; i++)sb.Append(hashValue[i].ToString("x2"));break;case 32:for (int i = 0; i < 16; i++){sb.Append(hashValue[i].ToString("x2"));}break;default:for (int i = 0; i < hashValue.Length; i++){sb.Append(hashValue[i].ToString("x2"));}break;}return sb.ToString();}[WebMethod(Description = "極光發(fā)送信息")]public string doSend(){IDictionary<string, string> parameters = new Dictionary<string, string>();string html = string.Empty;int sendno = 1;string receiverValue = "!!!!!!!!!";//這個是一個別名 int receiverType = 4;string appkeys = "ca9e556875921e4f5d9abdc6";//appkeyString input = sendno.ToString() + receiverType + "" + "fa618664993ec1b9707cdef4";//market keystring verificationCode = MD5Encrypt(input);string content = "{\"n_title\":\"" + "測試測試" + "\",\"n_content\":\"" + "推送新消息" + "\",\"n_builder_id\":\"1\",\"n_extras\":{\"nid\":\"" + 240 + "\"}}"; //發(fā)送的文本string loginUrl = "http://api.jpush.cn:8800/sendmsg/v2/sendmsg";parameters.Add("sendno", sendno.ToString());parameters.Add("app_key", appkeys);parameters.Add("receiver_type", receiverType.ToString());parameters.Add("verification_code", verificationCode); //MD5 parameters.Add("msg_type", "1");parameters.Add("msg_content", content); //內(nèi)容 parameters.Add("platform", "android,ios");HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, parameters, null, null, Encoding.UTF8, null);if (response != null){// 得到返回的數(shù)據(jù)流 Stream receiveStream = response.GetResponseStream();// 如果有壓縮,則進(jìn)行解壓 if (response.ContentEncoding.ToLower().Contains("gzip")){receiveStream = new GZipStream(receiveStream, CompressionMode.Decompress);}// 得到返回的字符串 html = new StreamReader(receiveStream).ReadToEnd();}return html;} } View Code然后調(diào)用方法即可。
至于服務(wù)器接收代碼,因為直接使用的極光上下載的3分鐘demo所以直接使用的demo中的接收方法。不用修改任何代碼手機(jī)端即可接收信息。
如果希望接收到消息之后能打開到對應(yīng)的頁面,則修改TestActivy.java代碼如下:【代碼未優(yōu)化~無用的沒刪除】
package com.example.jpushdemo;import org.apache.cordova.DroidGap; import org.json.JSONArray; import org.json.JSONObject;import cn.jpush.android.api.JPushInterface; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;public class TestActivity extends DroidGap {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TextView tv = new TextView(this);tv.setText("用戶自定義打開的Activity");Intent intent = getIntent();String path = "";if (null != intent) {Bundle bundle = getIntent().getExtras();String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);String content = bundle.getString(JPushInterface.EXTRA_ALERT);String extreaterjson = bundle.getString(JPushInterface.EXTRA_EXTRA);int index = extreaterjson.indexOf(":");String result = extreaterjson.substring(index+2, extreaterjson.length()-2);tv.setText("Title : " + title + " " + "Content : " + content+" 附加字段:"+result);path="file:///android_asset/www/blog-single.html?nid="+result;}addContentView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));super.loadUrl(path);}} View Code?
參考資料:http://hi.baidu.com/taobao458/item/4ec606f34f169156c9f33781
轉(zhuǎn)載于:https://www.cnblogs.com/Jokers/p/3568826.html
總結(jié)
以上是生活随笔為你收集整理的Phonegap 极光推送api 服务器端推送代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高并发系统数据库设计
- 下一篇: photoshop的页面制作练习1