How to send firebase notification to multiple topics - c#

I have done like below for single topic to send notification which is working great:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["FirebaseAPI"]);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
client.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue("key", "=" + ConfigurationManager.AppSettings["projectKey"]);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
//How to Send more Id's loop it with the array
var data = new
{
to = string.Concat("/topics/", 121),
notification = new
{
body = "test",
title = "FIRE alert"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
request.Content = new StringContent(json, Encoding.UTF8, "application/json");//CONTENT-TYPE header
var resultArray = client.PostAsync("send", request.Content);
return resultArray.Result.Content.ReadAsStringAsync();

Related

Send form-data in C# HttpClient

Hello, I am pulling data from an api with C# HttpClient. I need to pull data in form-data form with the post method. I wrote the code below but got an empty response. How can I do it?
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://myapi.com");
var content = new MultipartFormDataContent();
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value1", "myvalue1"),
new KeyValuePair<string, string>("value2", "myvalue2"),
new KeyValuePair<string, string>("value3", "myvalue3")
});
content.Add(dataContent);
request.Content = content;
var header = new ContentDispositionHeaderValue("form-data");
request.Content.Headers.ContentDisposition = header;
var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
var result = response.Content.ReadAsStringAsync().Result;
You're sending your data in an incorrect way by using FormUrlEncodedContent.
To send your parameters as MultipartFormDataContent string values you need to replace the code below:
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});
With this:
content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

Uploading image to ServiceNow in C# via REST API

I am trying to upload image to ServiceNow incident using SNow API provided in this link:
https://developer.servicenow.com/dev.do#!/reference/api/orlando/rest/c_AttachmentAPI#r_AttachmentAPI-POSTmultipart
I've written below C# code to post the image:
string url = "https://mycompany.service-now.com/api/now/attachment/upload/"
, userName = "MyUser", passwd = "MyPassword";
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(userName, passwd),
};
using (var httpClient = new HttpClient(httpClientHandler))
{
// Add an Accept header for JSON format.
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var multipartContent = new MultipartFormDataContent();
multipartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data");
multipartContent.Add(new StringContent("incident"), "table_name");
multipartContent.Add(new StringContent("f264fd3a1bghghgjjhg8f7b4bcbb6"), "table_sys_id"); // id of my incident
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("D:\\MyImage.jpeg")), "uploadFile", "MyImage.jpeg");
var response = httpClient.PostAsync(new Uri(url), multipartContent).Result;
string result = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(result);
}
However, I keep getting:
Requested URI does not represent any resource
What could be the problem and how to adjust the code accordingly?
After removing the "/" at the end of the url, and also adding double qoutes around the keys in the headers as I read from this post:
https://community.servicenow.com/community?id=community_question&sys_id=328614ffdb00eb808e7c2926ca9619ad&view_source=searchResult
The final working code is:
string url = "https://mycompany.service-now.com/api/now/attachment/upload"
, userName = "MyUser", passwd = "MyPassword";
var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(userName, passwd),
};
using (var httpClient = new HttpClient(httpClientHandler))
{
// Add an Accept header for JSON format.
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var fileStream = new ByteArrayContent(File.ReadAllBytes("D:\\Image.jpeg"));
fileStream.Headers.Remove("Content-Type");
fileStream.Headers.Add("Content-Type", "application/octet-stream");
fileStream.Headers.Add("Content-Transfer-Encoding", "binary");
fileStream.Headers.Add("Content-Disposition", $"form-data;name=\"uploadFile\"; filename=\"{"Image.jpeg"}\"");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("incident"), "\"table_name\"");
multipartContent.Add(new StringContent("f264fd3a1bghghgjjhg8f7b4bcbb6"), "\"table_sys_id\"");
multipartContent.Add(fileStream, "uploadFile");
var response = httpClient.PostAsync(new Uri(url), multipartContent).Result;
string result = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(result);
}

ReasonPhrase Not Acceptable HTTPClient C#

I am trying to send a json object with a base4 encoded file to a web api service using the code below
MemoryStream target = new MemoryStream();
q.fileUpload.InputStream.CopyTo(target); //q.fileUpload is an HttpPostedFilebase pdf
var myfile= Convert.ToBase64String(target.ToArray());
var requestbody = new {
filedata = new
{
mimetype = "application/pdf",
basedata = "base64-data=" + myfile
}
};
var jsondata = JsonConvert.SerializeObject(requestbody );
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://web.base.url/");
client.DefaultRequestHeaders.Add("X-API-KEY", "SOMEAPIKEY");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "upload");
request.Content = new StringContent(jsondata, Encoding.UTF8, "application/json");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var responsetask= client.SendAsync(request);
return Json(responsetask);
But i everytime i call this i get a 406 Not Acceptable response. Anyone knows what causes it?

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?
Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;
string json = JsonConvert.SerializeObject(bm);
MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
Or
var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(params)).Result;
var token = response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}

how to use HttpClient Async & Await to post FCM message

I am struggling to use HttpClient to post FCM message. I am getting invalid Header format exception. I can use WebRequest to post FCM message. But I want to try as Async and Await by using HttpClient.
Please suggest me which is best HttpClient or WebRequest.
<div>
<br>String uri;
<br>uri = "https://fcm.googleapis.com/fcm/send";
<br>var postData = new
<br>{
<br>to = DeviceID,
<br>data = new
{
MessageID = enquiryid
},<br>
<br>notification = new
{
body = enquirymessage,
title = FromUser,
icon = "myicon"
}<br>
};<br>
<br>var serializer = new JavaScriptSerializer();
<br>var json = serializer.Serialize(postData);<br>
<br>using (var client = new HttpClient())
<br>{
<p>client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue
("key", "=" + fcmDetails.SERVER_API_KEY);<br>
<p>client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue
("application/json"));
<p>client.DefaultRequestHeaders.Add("Sender: id ", "="+ fcmDetails.PROJECT_KEY);
<p>using (var r = client.PostAsJsonAsync(new Uri(uri), json))
<br>{
<br>string result = await r.Content.ReadAsStringAsync();
<br>sResponseFromServer= result;
}<br>
}
Replace the line in your code
client.DefaultRequestHeaders.Add("Sender: id ", "="+ fcmDetails.PROJECT_KEY);
with
client.DefaultRequestHeaders.Add("Sender", "id=" + fcmDetails.PROJECT_KEY);
Use the sample code
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://fcm.googleapis.com/fcm/");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "=" + fcmDetails.SERVER_API_KEY);
client.DefaultRequestHeaders.Add("Sender","id=" + fcmDetails.PROJECT_KEY);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
var data = new
{
to = DeviceID,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
request.Content = new StringContent(json,
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
var data1 = client.PostAsync("send", request.Content);
var d = data1.Result.Content.ReadAsStringAsync();

Categories