Bad Request sending gcm message - android

I am trying to send gcm message via C#.
I tried several times, but I get http:400-Bad request while trying to send it in json method.
When I try to send it in text, I can't read it (rtl language) - that's why I am trying JSON.
Anyone knows what the problem?
Thanks!
private static string SendNotificationJson2(string id, string msg)
{
var AuthString = "AIzaSyDAtmaqSdutBQemqmd4dQgf33B_6ssbvXA";
var RegistrationID = id;
var Message = msg;
//-- Create GCM request insted of C2DM Web Request Object --//
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
Dictionary<String, String> dict = new Dictionary<string, string>();
dict.Add("registration_ids", RegistrationID);
dict.Add("data", Message);
dict.Add("collapse_key", "1");
string postData = GetPostStringFrom(dict);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/json";
Request.ContentLength = byteArray.Length;
Request.Headers.Add("Authorization", "key=" + AuthString);
//-- Delegate Modeling to Validate Server Certificate --//
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
//Console.WriteLine("Response from web service not OK :");
//Console.WriteLine(((HttpWebResponse)Response).StatusDescription);
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return "ok";
}
private static string GetPostStringFrom(Dictionary<string,string> postFieldNameValue)
{
// return Newtonsoft.Json.JsonConvert.SerializeObject(postFieldNameValue);
return "\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";
}</code>

You forgot first bracket in Json data
use
return "{\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";
instead of
return "\"data\": {\"Message\": \"" + postFieldNameValue["data"] + "\"},\"registration_ids\":[\"" + postFieldNameValue["registration_ids"] + "\"]}";

Your registration ID needs to be a JSON array so use a list instead of a single string.

Related

fcm push notification to mobile with topic messaging using C#

We have an important requirement to push notification to more than 50000 mobile users (Android & IOS). We were implemented this by Topic Messaging. We created batch for every 998 users, and then push to the fcm using topic. But the delivery of push notification is inaccurate. Sometime, some devices get the notification message and some times, no devices. We were use only two topics, one for Android and other for IOS. Sending multiple batches(each batch contains 998 tokens) to the Same topic. Can you please share whats the issue behind this, or please share how to achieve the above scenario.
Batch Push
public string pushBatchbasedonTopic(string Topic, List<string> RegisterIds)
{
_basemobile.WriteToLog("\n Log pushBatchbasedonTopic: ","");
string topic = Topic;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://iid.googleapis.com/iid/v1:batchAdd");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
to = topic,
registration_tokens = RegisterIds.ToArray()
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log TopicCreation: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log topic creation error: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Trace topic creation: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n InnerException topic creation: " + ex.InnerException, "");
return str;
}
}
FCM Push
public string pushusingFCMforBatchAndroidBasedOnOneTopic(string Id, string Condition, string Message, string Type, string count)
{
_basemobile.WriteToLog("\n Log pushusingFCMforBatchAndroidBasedOnOneTopic: ", "");
string setcondition = Condition;
//string deviceId = DeviceToken;
string str = null;
try
{
string senderId = WebConfigurationManager.AppSettings["FCM_SENDER_ID"].ToString();
string applicationkey = WebConfigurationManager.AppSettings["FCM_KEY"].ToString();
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Timeout = 600000;
var dataser = new
{
//to = deviceId,
condition = setcondition,
data = new
{
Notification_Id = Id,
msg_type = Type,
Count = count,
sound = "Enabled",
body = Message,
badge = count
}
// count = 0,
//type = Type
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(dataser);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationkey));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
_basemobile.WriteToLog("\n Log tRequest: ", tRequest.ToString());
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
str = sResponseFromServer;
_basemobile.WriteToLog("\n Log sResponseFromServer: ", sResponseFromServer);
}
}
}
}
_basemobile.WriteToLog("\n Log pushfcmandroid: " + str, "");
return str;
}
catch (Exception ex)
{
str = ex.Message;
_basemobile.WriteToLog("\n Log errorios: " + ex.Message, "");
_basemobile.WriteToLog("\n Stack Traceios: " + ex.StackTrace, "");
_basemobile.WriteToLog("\n Inner Exceptionios: " + ex.InnerException, "");
return str;
}
}

Android hooking HTTPS traffic using Frida

I'm trying to learn Frida to hook into various application. Specifically I'm trying to hook into Android applications, I'm using the Appmon project. That project has an HTTPS.js script that hooks into the getInputStream and getOutputStream from the HttpUrlConnection class. The HTTPS.js script successfully hooks the methods, but when HTTPS traffic is sent the data that i see is encrypted.
According to Android documentation on HTTPUrlConnection if the URL.openconnection() method receives a HTTPS url it will return a HTTPSUrlConnection object.
Android documentation for HttpsURLConnection states it is an abstract class that extends HttpURLConnection.
public abstract class HttpsURLConnection extends HttpURLConnection
I searched the android source code and found HttpsURLConnection is abstract and is extended by DelegatingHttpsURLConnection which is also abstract. DelegatingHttpsURLConnection is extended by HttpsURLConnectionImpl
I've hooked into
com.android.okhttp.internal.huc.HttpsURLConnectionImpl
which is successful but the data is still encrypted. Here is the code
var HttpsURLConnection = Java.use("com.android.okhttp.internal.huc.HttpsURLConnectionImpl");
HttpsURLConnection.getInputStream.overloads[0].implementation = function() {
try {
methodURL = "";
responseHeaders = "";
responseBody = "";
var Connection = this;
var stream = stream = this.getInputStream.overloads[0].apply(this, arguments);
var requestURL = Connection.getURL().toString();
var requestMethod = Connection.getRequestMethod();
var requestProperties
methodURL = requestMethod + " " + requestURL;
if (Connection.getHeaderFields) {
var Keys = Connection.getHeaderFields().keySet().toArray();
var Values = Connection.getHeaderFields().values().toArray();
responseHeaders = "";
for (var key in Keys) {
if (Keys[key] && Keys[key] !== null && Values[key]) {
responseHeaders += Keys[key] + ": " + Values[key].toString().replace(/\[/gi, "").replace(/\]/gi, "") + "\n";
} else if (Values[key]) {
responseHeaders += Values[key].toString().replace(/\[/gi, "").replace(/\]/gi, "") + "\n";
}
}
}
var retval;
if (stream) {
var baos = ByteArrayOutputStream.$new();
var buffer = -1;
var BufferedReaderStream = BufferedReader.$new(InputStreamReader.$new(stream));
while ((buffer =stream.read()) != -1){
baos.write(buffer);
responseBody += String.fromCharCode(buffer);
}
BufferedReaderStream.close();
baos.flush();
retval = ByteArrayInputStream.$new(baos.toByteArray());
}
/* --- Payload Header --- */
var send_data = {};
send_data.time = new Date();
send_data.txnType = 'HTTPS';
send_data.lib = 'com.android.okhttp.internal.huc.HttpsURLConnectionImpl';
send_data.method = 'getInputStream';
send_data.artifact = [];
/* --- Payload Body --- */
var data = {};
data.name = "Request/Response";
data.value = methodURL + "\n" + requestHeaders + "\n" + requestBody + "\n\n" + responseHeaders + "\n" + responseBody;
data.argSeq = 0;
send_data.artifact.push(data);
send(JSON.stringify(send_data));
if(retval)
return retval;
return stream;
} catch (e) {
this.getInputStream.overloads[0].apply(this, arguments);
}
}
BTW I am planning on submitting a pull request once i get this working.
Android documentation has an example on how to create an HTTP request:
URL url = new URL("https://wikipedia.org");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);
Reading this tells me that just calling the getInputStream() method should return the clear text stream, but it doesnt appear to be doing so.
Question: How can i get the clear text data from the HTTPS traffic? I can see the headers, just not the actual data
Update 10/13
I'm wondering if the data I'm seeing isn't encrypted, just encoded. Here is a snipping of the data i receive back:
\\u001f\x8b\\b\\u0000\\u0000\\u0000\\u0000\\u0000\\u0004\\u0000\xed\xbd\\u0007`\\u001cI\x96%&/m\xca{\x7fJ\xf5J\xd7\xe0t\xa1\\b\x80`\\u0013$\xd8\x90#\\u0010\xec\xc1\x88\xcd\xe6\x92\xec\\u001diG#)\xab*\x81\xcaeVe]f\\u0016#\xcc\xed\x9d\xbc\xf7\xde{\xef\xbd\xf7\xde{\xef\xbd\xf7\xba;\x9dN\'\xf7\xdf\xff?\\\\fd\\u0001l\xf6\xceJ\xda\xc9\x9e!\x80\xaa\xc8\\u001f?~|\\u001f?\\"\\u001e\xff\\u001e\xef\\u0016ez\x99\xd7MQ-?\xfbhw\xbc\xf3Q\x9a/\xa7\xd5\xacX^
The response header indicates that its gzip encoded
Content-Encoding: gzip
Content-Length: 438
Content-Type: text/xml; charset=utf-8
I wonder if its related to this stackoverflow answer, although the outgoing request does have the "Accept-Encoding: gzip" header. I tried adding a call to GZIPInputStream, but the application doesnt like the response
Update 2
So I am able to get it to capture the data, it is a problem with gzip. The problem I'm running into now is that the application on the Android device expcts a GZIPed input stream. To display the data within Frida i have to run it through GZIPInputStream, not sure yet how to compress it again to send to the app. I tried breifly with GZIPOutputStream but that didnt work. Here is my updated code.
HttpURLConnection.getInputStream.overloads[0].implementation = function() {
try {
methodURL = "";
responseHeaders = "";
responseBody = "";
var Connection = this;
if("gzip" == Connection.getContentEncoding())
{
var stream = InputStreamReader.$new(GZIPInputStream.$new(this.getInputStream.apply(this, arguments)));
}
else
{
var stream = InputStreamReader.$new(this.getInputStream.apply(this, arguments));
}
}
var requestURL = Connection.getURL().toString();
var requestMethod = Connection.getRequestMethod();
var requestProperties
methodURL = requestMethod + " " + requestURL;
if (Connection.getHeaderFields) {
var Keys = Connection.getHeaderFields().keySet().toArray();
var Values = Connection.getHeaderFields().values().toArray();
responseHeaders = "";
for (var key in Keys) {
if (Keys[key] && Keys[key] !== null && Values[key]) {
responseHeaders += Keys[key] + ": " + Values[key].toString().replace(/\[/gi, "").replace(/\]/gi, "") + "\n";
} else if (Values[key]) {
responseHeaders += Values[key].toString().replace(/\[/gi, "").replace(/\]/gi, "") + "\n";
}
}
}
var retval;
if (stream) {
var baos = ByteArrayOutputStream.$new();
var buffer = -1;
var BufferedReaderStream = BufferedReader.$new(stream);
while ((buffer =stream.read()) != -1){
baos.write(buffer);
responseBody += String.fromCharCode(buffer);
}
BufferedReaderStream.close();
baos.flush();
if("gzip" == Connection.getContentEncoding())
{
retval = GZIPOutputStream.$new(ByteArrayInputStream.$new(baos.toByteArray()));
}
else
{
retval = ByteArrayInputStream.$new(baos.toByteArray());
}
}
/* --- Payload Header --- */
var send_data = {};
send_data.time = new Date();
send_data.txnType = 'HTTP';
send_data.lib = 'com.android.okhttp.internal.http.HttpURLConnectionImpl';
send_data.method = 'getInputStream';
send_data.artifact = [];
/* --- Payload Body --- */
var data = {};
data.name = "Request/Response";
data.value = methodURL + "\n" + requestHeaders + "\n" + requestBody + "\n\n" + responseHeaders + "\n" + responseBody;
data.argSeq = 0;
send_data.artifact.push(data);
send(JSON.stringify(send_data));
if(retval)
return retval;
return stream;
} catch (e) {
this.getInputStream.overloads[0].apply(this, arguments);
}
}

Android: Generate Oauth1 Signature in Volley Request

I am trying to add Oauth1 Authorization in my android app using volley
in the postman when i add the details like oauth_consumer_key, oauth_consumer_secret , token_key token_secret like the picture below
it generate a header like below picture and response received successfully.
Postman generated header
Authorization:OAuth oauth_consumer_key="4e77abaec9b6fcda9kjgkjgh44c2e1",oauth_token="2da9439r34104293b1gfhse2feaffca9a1",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1482470443",oauth_nonce="cCbH5b",oauth_version="1.0",oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Problem
I googled a lot to create oauth signature like postmasn created to attach volley ServerConnectionChannel but failed.
oauth_signature="A1QPwTATVF4x3cN0%2FN46CZrtSKw%3D"
Current code
public void doSendJsonRequest(final ERequest ERequest) {
requestMethod = String.valueOf(ERequest.method);
requestUrl = String.valueOf(ERequest.mReqUrl);
if(requestMethod.equals(Request.Method.GET)){
requestMethod = "GET";
}else if(requestMethod.equals(Request.Method.POST)){
requestMethod = "POST";
}else if(requestMethod.equals(Request.Method.PUT)){
requestMethod = "PUT";
}else if(requestMethod.equals(Request.Method.DELETE)){
requestMethod = "DELETE";
}
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString();
final String kk = requestMethod+"&" + encode(requestUrl)+"&";
final String kk = encode("GET"+"&"
+ requestUrl+"&"
+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\"&"
+OAUTH_NONCE + "=\"" + getNonce()+ "\"&"
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\"&"
+OAUTH_TIMESTAMP + "=\"" + ts + "\"&"
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\"");
RequestQueue queue = VolleyUtils.getRequestQueue();
try {
JSONObject jsonObject = ERequest.jsonObject;
EJsonRequest myReq = new EJsonRequest(ERequest.method, ERequest.mReqUrl, jsonObject, createReqSuccessListener(ERequest), createReqErrorListener(ERequest)) {
public Map < String, String > getHeaders() throws AuthFailureError {
// Long tsLong = System.currentTimeMillis()/1000;
// String ts = tsLong.toString();
String strHmacSha1 = "";
String oauthStr = "";
strHmacSha1 = generateSignature(kk, oAuthConsumerSecret, oAuthTokenSecret);
strHmacSha1 = toSHA1(strHmacSha1.getBytes());
Log.e("SHA !",strHmacSha1);
oauthStr ="OAuth "+ OAUTH_CONSUMER_KEY + "=\"4e77abaec9b6fcda9b11e89a9744c2e1\","
+OAUTH_TOKEN +"=\"2da943934104293b167fe2feaffca9a1\","
+OAUTH_SIGNATURE_METHOD + "=\""+OAUTH_SIGNATURE_METHOD_VALUE+"\","
+OAUTH_TIMESTAMP + "=\"" + ts + "\","
+OAUTH_NONCE + "=\"" + getNonce()+ "\","
+OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\","
+OAUTH_SIGNATURE + "=\"" + strHmacSha1+ "\"";
Log.e("VALUE OF OAuth str",oauthStr);
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization",oauthStr);
// params.put("Authorization",getConsumer().toString());
return params;
}
};
myReq.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 4,
BABTAIN_MAX_RETRIES,
BABTAIN_BACKOFF_MULT));
myReq.setHeader("Cache-Control", "no-cache");
//myReq.setHeader("Content-Type", "application/json");
queue.add(myReq);
} catch (Exception e) {
e.printStackTrace();
}
private String generateSignature(String signatueBaseStr, String oAuthConsumerSecret, String oAuthTokenSecret) {
byte[] byteHMAC = null;
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec spec;
if (null == oAuthTokenSecret) {
String signingKey = encode(oAuthConsumerSecret) + '&';
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
} else {
String signingKey = encode(oAuthConsumerSecret) + '&' + encode(oAuthTokenSecret);
spec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
}
mac.init(spec);
byteHMAC = mac.doFinal(signatueBaseStr.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String base64 = Base64.encodeToString(byteHMAC, Base64.DEFAULT);
return base64.trim();
}
private String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
private String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++)
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
return result;
}
this code create a signature like :oauth_signature="42a611860e29e893a435b555e7a9559a704f4e94" and it failed to get autherization.
getting error like : BasicNetwork.performRequest: Unexpected response code 401 for url
?How to generate oauth_signature like postman provided using volley..
?how can i improve this code ?Is any libraries or default function to do that
?How we add oauth1 signature in volley..
Please Help.. Thank you
I just found a github example for generating signature corresponding to nonce in Oauth1 and successfully integrate into my project
here is the link : https://github.com/rameshvoltella/WoocommerceAndroidOAuth1

Remote Controlling the Android App from Web Application (ASP.Net)

I would like to start/stop the video recording automatically by sending notification from Web Server (Web Application) to Android App. What would be best approach?
I have following approaches in my mind:
Opening Web sockets using Signal R Approach.
SMS Messaging (App will have SMS receiver event, start/stop recording based on messages).
using FCM you send notification on Android App from .net Application:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Uploadfirebasedata(string firebaseid, string emailid,string Operation)
{
int ret = 0;
string suc = "success";
// XmlDocument xmlupdatedoc = new XmlDocument();
SqlParameter[] param =
{
new SqlParameter("#firebaseid", DbType.String),
new SqlParameter("#emailid", DbType.String),
new SqlParameter("#Operation", DbType.String),
};
param[0].Value = firebaseid;
param[1].Value = emailid;
param[2].Value = Operation;
string SERVER_API_KEY = "YOUR SERVER API KEY";
var SENDER_ID = "YOUR SENDER ID";
var value = "Hi this is from HRM Team";
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
//tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
//tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
//string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" +firebaseid + "";
//Console.WriteLine(postData);
//Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var data = new
{
to = firebaseid,
notification = new
{
body = value,
title = "HRM",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
// return sResponseFromServer;
ret = objdata.ExecuteNonQuery("SP_TestWebServiceOperation", param);
if (ret == 1)
{
HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(suc + sResponseFromServer));
// xmlupdatedoc.LoadXml("<root><item>Successful</item></root>");
}
else
{
//xmlupdatedoc.LoadXml("<root><item>Unsuccessful</item></root>");
}
}
first you have register your app on to firebase console.
get token from android app using webservice

failed to using google GCM in android and .NET

I try to use GCM in my asp.net and android project.
it takes about 3days and nothing change.
what's wrong with my codes?
I'm really confused...
android side: onCreate
static final String GOOGLE_SENDER_ID = "tokyo-hghgf93712";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final String regIde = GCMRegistrar.getRegistrationId(this);
if (regIde.equals("")) {
GCMRegistrar.register(this, GOOGLE_SENDER_ID);
Log.v(regIde, "Done!");
} else {
Log.v(regIde, "Already registered");
}
.....
asp.net many of my function
function 1:
public void SendCommandToPhone(String sCommand)
{
String DeviceID = ";
// DeviceID = "THE DEVICE ID YOU ARE SENDING TO";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "tokyo-hghgf93712"));
String collaspeKey = Guid.NewGuid().ToString("n");
//String postData=string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, "Pickup Message", collaspeKey);
String postData = string.Format("registration_id={0}&data.payload={1}&collapse_key={2}", DeviceID, sCommand, collaspeKey);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
function 2:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string BrowserAPIKey = "AIzaSygfdgdfgdfgfdgdfpjxgcw";
string message = "monaaaaaaa";
string tickerText = "test";
string contentTitle = "title";
string postData = "{ \"registration_ids\": [ \"" + tbRegistrationID.Text + "\" ], \"data\": {\"tickerText\":\"" + tickerText + "\", \"contentTitle\":\"" + contentTitle + "\", \"message\": \"" + message + "\"}}";
string response = SendGCMNotification(BrowserAPIKey, postData);
litResult.Text = response;
}
}
/// <summary>
/// Send a Google Cloud Message. Uses the GCM service and your provided api key.
/// </summary>
/// <param name="apiKey"></param>
/// <param name="postData"></param>
/// <param name="postDataContentType"></param>
/// <returns>The response string from the google servers</returns>
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
{
// from here:
// http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
//
// original:
// http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
// Request.Headers.Add(string.Format("Sender: id={0}", "5637737476457"));
// Request.Headers.Add(string.Format("Authorization: key={0}", "5637737476457"));
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
function 3:
public void SendNotification(string data)
{
string RegId =
";
string ApplicationID = "AIzaSygfdgdfgdfgfdgdfpjxgcw";
string SENDER_ID = "5637737476457";
var value = "Lokesh"; //message text box
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
//Data post to the Server
string postData =
"collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() +
"&registration_id=" + RegId + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd(); //Get response from GCM server
//label_Result.Text = sResponseFromServer; //Assigning GCM response to Label text
tReader.Close(); dataStream.Close();
tResponse.Close();
}

Categories

Resources