HttpWebRequest doesn't work every time - c#

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");

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!

HttpWebRequest get the same response object when it's called in the second time

I am using HttpWebRequest to get webpage source code with POST method.
The page needs to be accessed for multiple times with different parameters.
When getting response in the second time in a short period, it always return the same response object to me. After debugging, if the second call is after around 30 seconds, the request can get the correct response object(source code).
public HtmlAgilityPack.HtmlDocument getHtmlData(string url, string cname)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
try
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Headers[HttpRequestHeader.CacheControl] = "no-cache";
req.Headers[HttpRequestHeader.Pragma] = "no-cache";
req.IfModifiedSince = DateTime.Now;
req.CachePolicy = noCachePolicy;
//add post data
string postData = "cname=" + cname;
byte[] byteArray = Encoding.GetEncoding("shift-jis").GetBytes(postData);
req.ContentLength = byteArray.Length;
using (Stream stream = req.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
// get response
string data = "";
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift-jis"));
data = reader.ReadToEnd();
reader.Close();
}
response.Close();
doc.LoadHtml(data);
//System.Threading.Thread.Sleep(30000);
}
catch(Exception ex)
{
Log.log.Debug(ex.ToString());
}
return doc;
}
Function call block:
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01sli00/AF");
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00999999/B3");
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00201604/E3");
I have stuck with the problem for a whole day. hope someone can give me a clue.
Many thanks!

Remote Server returns error 401 Unauthorized Webexception (POST)

I'm trying to solve an issue that I Mostly (70%) have (30% is succesfull).
I trying to do a webrequest (POST) with the following code:
private string HttpWebRequest(string busStopCode)
{
//XML input
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>"+busStopCode+"</MonitoringRef></StopMonitoringRequest></ServiceRequest></Siri>";
string responseFromServer = null;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://<username>:<username>#nextbus.mxdata.co.uk/nextbuses/1.0/1");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultNetworkCredentials;
// Create POST data and convert it to a byte array.
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
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();
// Get the response.
WebResponse response = null;
while (response == null)
{
try
{
response = request.GetResponse();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription + " Completed");
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
When I call this function I get mostly a messagebox of my exception with:
"System.Net.WebException: The remote Server returned an error(401) not authorized with System.Net.Http.Webrequest.GetResponse() with WindowsFormApplication1.Form1.HttpWebRequest(string BusstopCode) in <my pathfile>...."
What I'm doing wrong?
I already tried several solutions from previous threads but without success...
Thanks!

C# 405 methods not allowed

I am posting data to a website and displaying the resulting json data,
This is the function I ended up with after taking some pieces from msdn's example
private string request(string url, string data)
{
byte[] byteArray;
string postData,
responseFromServer;
WebResponse response;
Stream dataStream;
StreamReader reader;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Proxy = new WebProxy(ip, port);
responseFromServer = string.Empty;
request.Method = "POST";
request.Timeout = 10000;
postData = data;
byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
try
{
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception x)
{
x.ToString();
}
return responseFromServer;
}
}
The ip and port variables are within the class that this function is inside of.
When GetResponse() is called, it this exception.
{System.Net.WebException: The remote server returned an error: (405) Method Not Allowed.
Ive tested it and it is only because of the proxy, but the parameters are correct.
Why is this exception being thrown?

Categories

Resources