Google Clound Messaging server C# - google-cloud-messaging

I want to send message to GCM and I receive unavailable with status 200. What am I doing wrong?
var GoogleAppID = "";
var DeviceID = "";
var request = WebRequest.Create("https://android.googleapis.com/gcm/send");
request.Method = "POST";
request.Headers.Add("Authorization", "key=" + GoogleAppID);
request.ContentType = "application/json";
var message = new Message();
message.registration_ids.Add(DeviceID);
message.data.Add("gcm_message", "12345");
var jsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(message);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonMessage);
request.ContentLength = byteArray.Length;
var reqStream = request.GetRequestStream();
reqStream.Write(byteArray, 0, byteArray.Length);
var response = request.GetResponse();
var 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";
}
var responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream);
var responseContent = streamReader.ReadToEnd();
streamReader.Close();

No need to build your own library, github already has one. Use the following.
https://github.com/Redth/GCMSharp

Related

The server committed a protocol violation. Section=ResponseStatusLine : Issue

I created ASP.NET core 6 API project and used JWT authentication for each API end point.
But while executing in some physical system works fine but some other physical system and server throws below error
The server committed a protocol violation. Section=ResponseStatusLine
Sample Code
var request = (HttpWebRequest)WebRequest.Create(endpoint);
var token = System.Threading.Tasks.Task.Run(async() => await new Token("URL", "username", "pwd"])).Result;
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "POST";
var postData = JsonConvert.SerializeObject(Details, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.ASCII.GetBytes(postData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var responses = (HttpWebResponse)request.GetResponse();
Sample code based on HTTP Client
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), endpoint))
{
string token = SalesOperationAPIToken("url", "usertest", "pwd");
request.Headers.TryAddWithoutValidation("accept", "*/*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
string json = JsonConvert.SerializeObject(Details);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = httpClient.SendAsync(request).Result;
var responseMessage = response.Content.ReadAsStringAsync().Result;
}
}
I am not sure what configuration need to be changed to get this worked in all system.
Thanks in advance.

Google API Calendar OAUTH2 The remote server returned an error: (404) Not Found

async void GetEvent(string access_token) {
String serviceURL = "https://www.googleapis.com/calendar/v3/calendars/{email}/events";
String url = string.Format(serviceURL + "&key={0}&scope={1}", clientSecret, "https://www.googleapis.com/auth/calendar.events.readonly");
// sends the request
HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(url);
userinfoRequest.Method = "GET";
userinfoRequest.Headers.Add(string.Format("Authorization: Bearer {0}", access_token));
userinfoRequest.ContentType = "application/json";
userinfoRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
userinfoRequest.UseDefaultCredentials = true;
userinfoRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// gets the response
WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync();
using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream())) {
// reads response body
string userinfoResponseText = await userinfoResponseReader.ReadToEndAsync();
output(userinfoResponseText);
}
}

The request was aborted could not create ssl/tls secure channel. httpwebrequest

I'm using an approach I found on Google that does not work as I hoped.
string resultxml = string.Empty;
#region First Link code
try
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//Header Settings
req.Method = "POST"; // Post method
req.ContentType = "text/xml";// content type
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
//Certificate with private key
String certificateFileNameWithPath = "C:\\JPCertificates\\test.pfx";
String certificatePassword = "password";
X509Certificate2 cert = new X509Certificate2(certificateFileNameWithPath, certificatePassword);
req.ClientCertificates.Add(cert);
req.PreAuthenticate = true;
String XML = Xml;// "Test Message";//reader.ReadToEnd();
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
// Wrap the request stream with a text-based writer
Stream writer = req.GetRequestStream();
// Write the XML text into the stream
writer.Write(buffer, 0, buffer.Length);
writer.Close();
WebResponse rsp = req.GetResponse();
StreamReader responseStream = new StreamReader(rsp.GetResponseStream());
#endregion
}
catch (Exception ex)
{
throw ex;
}
return resultxml;
//Send the SOAP message StreamWriter stm = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
stm.Write(requestXML);
stm.Flush();
stm.Close();
//Send the SOAP message StreamWriter stm = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
stm.Write(requestXML);
stm.Flush();
stm.Close();

Upload File Without Multipart/Form-Data Using RestSharp

Below, there is a POST Request Done With Standard HttpWebRequest , and HttpWebResponse. Basically it post binanry file with some parameters.
How Can I do The Same Thing With RestSharp ?
Source:
https://github.com/attdevsupport/ATT_APIPlatform_SampleApps/tree/master/RESTFul/SpeechCustom, ATT_APIPlatform_SampleApps/RESTFul/Speech/Csharp/app1/ ]
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty+parEndPoint );
httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
if (!string.IsNullOrEmpty(parXArgs))
{
httpRequest.Headers.Add("X-Arg", parXArgs);
}
string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
httpRequest.ContentLength = binaryData.Length;
httpRequest.ContentType = contentType;
httpRequest.Accept = "application/json";
httpRequest.Method = "POST";
httpRequest.KeepAlive = true;
httpRequest.SendChunked = parChunked;
postStream = httpRequest.GetRequestStream();
postStream.Write(binaryData, 0, binaryData.Length);
postStream.Close();
HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
A simple upload example:
RestClient restClient = new RestClient("http://stackoverflow.com/");
RestRequest restRequest = new RestRequest("/images");
restRequest.RequestFormat = DataFormat.Json;
restRequest.Method = Method.POST;
restRequest.AddHeader("Authorization", "Authorization");
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", imageFullPath);
var response = restClient.Execute(restRequest);

HTTP post contentlength error

I have a script sending a multi part mime ie a a soap with attachments. I am using C# httpWebRequest class. I am getting an error that says the content length is required yet I am setting the content length dynamically in my code using webrequest's contentLength property. any ideas why this could be? thanx!
this is the code:
public void sendSOAPoverHttpVoda()
{
try
{
string xmlDoc = this.soapXml;
byte[] bytes;
bytes = Encoding.UTF8.GetBytes(xmlDoc);
long contentSize = bytes.Length;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(conectionUrl);
req.SendChunked = true;
CredentialCache credentialCacheObj = new CredentialCache();
credentialCacheObj.Add(
new Uri(conectionUrl),
"Basic", new NetworkCredential("dddfff", "dddddd"));
credentialCacheObj.Add(new Uri(conectionUrl), "Digest", new NetworkCredential("dddfff", "dddddd"));
req.Credentials = credentialCacheObj;
req.Method = "POST";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = xmlDoc.Length;
req.ContentType = "multipart/related; boundary=\"----=cellsmart_mm7_SOAP\";type=\"text/xml\";Start=\"</cellsmart_mm7_submit>\"";
req.AllowWriteStreamBuffering = true;
req.Timeout = 20000;
req.Headers.Add("SOAPAction", "");
//req.Connection = "";
if (bytes != null)
{
using (Stream outputStream = req.GetRequestStream())
{
outputStream.Write(bytes, 0, xmlDoc.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseText = reader.ReadToEnd();
Console.WriteLine("Response received from URI : " + responseText);
Console.ReadLine();
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error : " + ex.Message + "\n" + ex.StackTrace);
Console.ReadLine();
}
}
The error/exception i get is COntent length required (411)
You can't use both SendChunked=true and ContentLength. The easiest thing to do would be to use a chunked response and omit the ContentLength. You could also retain the ContentLength and omit the SendChunked if you want though.
In case you're not familiar with it, wikipedia has a nice description of chunking.
You declare contentLength as the length of the byte[] that you send ('bytes') and then you use the length of xmlDoc as the content length - which will give a different length than actual. Then you use the same xmlDoc.Length in outputStream.Write.
Why are you not using bytes.Length in both cases? Or contentLength which you've declared but never used, I believe that is your problem, you are sending xmlDoc.Length (Length of a string) for bytes.Length (length of a byte array converted from a string), so when the file is longer than expected by the sent length, the error returns.
Try this:
public void sendSOAPoverHttpVoda()
{
try
{
string xmlDoc = this.soapXml;
byte[] bytes;
bytes = Encoding.UTF8.GetBytes(xmlDoc);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(conectionUrl);
req.SendChunked = true;
CredentialCache credentialCacheObj = new CredentialCache();
credentialCacheObj.Add(
new Uri(conectionUrl),
"Basic", new NetworkCredential("dddfff", "dddddd"));
credentialCacheObj.Add(new Uri(conectionUrl), "Digest", new NetworkCredential("dddfff", "dddddd"));
req.Credentials = credentialCacheObj;
req.Method = "POST";
req.ProtocolVersion = HttpVersion.Version11;
req.ContentLength = bytes.Length;
req.ContentType = "multipart/related; boundary=\"----=cellsmart_mm7_SOAP\";type=\"text/xml\";Start=\"</cellsmart_mm7_submit>\"";
req.AllowWriteStreamBuffering = true;
req.Timeout = 20000;
req.Headers.Add("SOAPAction", "");
//req.Connection = "";
if (bytes != null)
{
using (Stream outputStream = req.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseText = reader.ReadToEnd();
Console.WriteLine("Response received from URI : " + responseText);
Console.ReadLine();
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error : " + ex.Message + "\n" + ex.StackTrace);
Console.ReadLine();
}
}