Push Notification for Nokia nid using c# - c#

i am working to sent a push message to Nokia phone from my c# project and i already put all the variables needed in my code but i handle an error Bad Request, i didn't understand its reason.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
//notification ID string i will get i from OVI
notID = System.Web.HttpUtility.UrlEncode(notID);
string url = "https://alpha.one.ovi.com/nnapi/1.0/nid/" +(notID);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Credentials = new NetworkCredential(ServiceId, service_secret);
request.ContentType = "application/x-www-form-urlencoded";
request_parameters = System.Web.HttpUtility.UrlEncode(request_parameters);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] buffer = encoding.GetBytes(request_parameters);
Stream newStream = request.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream);
MessageBox.Show("response=========" + sr.ReadToEnd());
sr.Close();
resStream.Close();
}
else
{
MessageBox.Show("message====" + response.StatusCode);
}
}
}

Please check the following project: https://projects.forum.nokia.com/dotnet_notifications_api
It is a .NET wrapper for the Nokia Notifications API.

Related

c# HttpWebRequest get response string

I'm trying to send some data through HTTPS Post without certification.
But I'm getting null however that response status code is OK.
Why is this? Any help would be greatly appreciated.
I want to receive "hello" string from https://test.com/post_test.php.
I saw many examples related to this, but none is working for me.
Does anyone know what I am missing?
Can some one guide me how to do that?
Thanks in advance!
c# code:
private static bool ValidateRemoteCertificate(object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors policyErrors)
{
return true;
}
private String SendHttpWebPost(string strUrl, string strData)
{
string result = string.Empty;
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
Uri url = new Uri(strUrl);
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
request.Timeout = 5000;
// encoding
byte[] data = Encoding.UTF8.GetBytes(strData);
request.ContentType = "application/json";
request.ContentLength = data.Length;
// send request
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Flush();
dataStream.Close();
// get response
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string strStatus = ((HttpWebResponse)response).StatusDescription;
StreamReader streamReader = new StreamReader(responseStream);
result = streamReader.ReadToEnd();
// close connection
streamReader.Close();
responseStream.Close();
response.Close();
}
catch (Exception ex)
{
return ex.Message;
}
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(SendHttpWebPost("https://test.com/post_test.php", "data=hello"));
}
php code:
<?php
echo($_REQUEST["data"]);
?>
Why don't you just simply request the Url without any fancy?
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(strUrl);
Request.Method = "GET";
Request.KeepAlive = true;
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
if (Response.StatusCode == HttpStatusCode.OK) {
....
}

c# How to send HTTP command as this - http://192.168.10.1/api/control?alert=101002

I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!

Windows Phone 8.1 and HTTP POST Request

I'm trying to post data to a web server with such code:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
//request.CookieContainer = new CookieContainer();
//request.CookieContainer.Add(new Uri(uri), new Cookie());
string postData = parameters.ToQueryString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream dataStream = await request.GetRequestStreamAsync())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = await request.GetResponseAsync();
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
return await reader.ReadToEndAsync();
}
}
catch (Exception e)
{
return e.Message + e.StackTrace;
}
Those bits of information that I found on the Internet suggest that it's because response headers are incorrect, but it's not for sure.
Could you please tell how to do http post request with parameters and if suggestion described above is correct, how to tell system.net not to check response headers?
This is how I'm calling this method:
Dictionary<string, string> par = new Dictionary<string, string>();
par.Add("station_id_from", "2218000");
par.Add("station_id_till", "2200001");
par.Add("train", "112Л");
par.Add("coach_num", "4");
par.Add("coach_class", "Б");
par.Add("coach_type_id", "3");
par.Add("date_dep", "1424531880");
par.Add("change_scheme", "0");
debugOutput.Text = await Requests.makeRequestAsync("http://booking.uz.gov.ua/purchase/coach", par);

Server Not Found 404 in Application to read data from api But without passing parameters it works

I got one more question related to api I'm working on :p
My problem is that the application i made to read the data works perfectly when the url is all passed, but if i want to pass the general url + parameters it doesn't...
Code with Full URL
private void btn_Api_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://MyIP/api/Employee/?FirstName=Jorge");
request.Method = "POST";
string postData = "";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseValue = string.Empty;
// grab the response
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
if (responseValue != "")
{
string _txtFileNew = #"C:\Users\Jorge.Leite\Documents\teste\" + txt_First.Text + ".txt"; //+txt_Last.Text + ".txt";
StreamWriter _srEannew = new StreamWriter(_txtFileNew);
_srEannew.WriteLine(responseValue);
_srEannew.Close();
}
}
}
catch (WebException ex)
{
// Handle error
}
Code with Url + parameters later PS: postData is passing the correct string ("?FirstName=Jorge") Jorge is the input Name
private void btn_Api_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MyIP/api/Employee/");
request.Method = "POST";
string postData = string.Format("?FirstName=" + txt_First.Text);
byte[] data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.ContentLength = data.Length;
When using this code it has an exception server not found 404
I really don't know what going on with this :\
Thank you in advance
Web API with POST methods do not work as smooth as with GET methods.
Check this other link to know a bit more Reading FromUri and FromBody at the same time

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

Categories

Resources