Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace HttpRequestExceptions
- {
- class Program
- {
- private Timer connectionTimer; // Normaly we use DispatcherTimer
- private int connectionTimerInterval = 1000; // ms
- // Normally there would be valid url (something like this
- // http://192.168.1.2/goform/ReadWrite), but right now we will simulate
- // request timeout with malformed url.
- const string url = "malformedURL";
- // Connection query just for completeness.
- // Right now it does not affect exceptions.
- readonly string connectedQuery = "redirect=/response.asp&variable=controlxp.axes.Running&value=none&read=1";
- public Program()
- {
- connectionTimer = new Timer(_ => ConnectionTimer_Tick(), null, 0, connectionTimerInterval);
- }
- private async void ConnectionTimer_Tick()
- {
- connectionTimer.Change(Timeout.Infinite, Timeout.Infinite);
- await CheckConnection();
- connectionTimer.Change(connectionTimerInterval, connectionTimerInterval);
- }
- private async Task CheckConnection()
- {
- try
- {
- // Right now we don't care about content of response.
- // We only care if we got something.
- string response = await SendRequestAsync(connectedQuery);
- }
- catch (Exception ex) // For now we will catch everything.
- {
- // Normaly this code is used in WPF application.
- System.Console.WriteLine("Set controls enabled to false");
- }
- }
- // Asynchronously sends HttpRequest with given data.
- // Here Exceptions are thrown. Basically any exception from this
- // method we don't care about and don't want to see in output window.
- private async Task<string> SendRequestAsync(string postData)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- byte[] data = Encoding.ASCII.GetBytes(postData);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = data.Length;
- using (Stream stream = await request.GetRequestStreamAsync())
- {
- await stream.WriteAsync(data, 0, data.Length);
- }
- string responseString;
- using (WebResponse response = await request.GetResponseAsync())
- using (StreamReader reader = new StreamReader(response.GetResponseStream()))
- {
- responseString = await reader.ReadToEndAsync();
- }
- return responseString;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- System.Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement