c# HttpWebRequest get response string - c#

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) {
....
}

Related

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!

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?

HttpWebRequest doesn't work every time

I'm doing a WebRequest to a Uri but the problem is that I don't get a response every time. Sometimes I need to redo it. I would like my program to check if it got no response and if so the program will automatically recall the method for the WebRequest until I get a response.
In pseudocode
while(response == null)
{
try it again
}
This is my function. The capital comment is the explanation of my issue
private string HttpWebRequest()
{
string xml = #"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Siri version='1.0' xmlns='http://www.siri.org.uk/'>
<ServiceRequest>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<RequestorRef><USERNAME></RequestorRef>
<StopMonitoringRequest version='1.0'>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<MessageIdentifier>12345</MessageIdentifier>
<MonitoringRef>020035811</MonitoringRef>
</StopMonitoringRequest>
</ServiceRequest>
</Siri>";
string responseFromServer = null;
WebRequest request = WebRequest
.Create("http://<USERNAME>:<PASSWORD>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
request.Method = "POST";
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
////////IF I GET NO RESPONSE EVERYTHING AFTER THE NEXT LINE WILL BE IGNORED
WebResponse response = request.GetResponse();
///////////THIS MESSAGEBOX WILL BE IGNORED
MessageBox.Show(((HttpWebResponse)response).StatusDescription+" Completed");
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
How can I resolve this?
If you want to just retry if the returned result ends up being null.. why not just do something like:
private void RunWebrequest()
{
if (HttpWebRequest() == null)
{
RunWebrequest();
}
else
{
//continue
}
}
I had the same 401 issue with this server, instead of placing your username & password in the url as per the traveline documentation use "Credentials" instead:-
string travelineUrl = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
var travelineRequest = (HttpWebRequest)WebRequest.Create(travelineUrl);
travelineRequest.Credentials = new NetworkCredential("yourusername", "yourpassword");

Push Notification for Nokia nid using 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.

How to get value back from a web services in C#?

I am sending a URL and XML to a webservices, so that it will return me JSON about the result. I am here posting the request to the webservices how do I get the value from the webservices back. The value returned by the webservices is JSON. What should be the return type here and what should be returned to get the HTTP response status and body
public string HttpPostcredentials(string XML, string url)
{
try
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
req.ContentType = "application/xml";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
}
catch (Exception e)
{
}
return null;
}
Is this what you are looking for:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = "POST";
}
byte[] requestBodyBytes = Encoding.ASCII.GetBytes(XML);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
You need to get the Response from the HttpWebRequest
WebResponse result = req.GetResponse();

Categories

Resources