HttpWebRequest.GetResponse() timeout issue - c#

I get intermittent timeout issue with getting a response from HttpWebRequest.GetResponse(). I thought it was an issue with the server, but the server seems to have sent the response within a minute. I have set timeout to be 20 mins.
GetResponse() keeps on waiting and then throws:
The operation has timed out.
I have also used GetRequestStream(), GetResponse() in using blocks. So, I don't think that could be an issue. The issue seems very sporadic. Any help would be appreciated.
var request = WebRequest.CreateHttp("http://someurl")
request.Method = "POST";
request.ContentLength = data.Length;
request.ContentType = "text/xml; encoding='utf-8'";
request.KeepAlive = false;
request.Timeout = 1200 * 1000;
request.ServicePoint.ConnectionLeaseTimeout = request.Timeout;
request.ServicePoint.MaxIdleTime = request.Timeout;
using (System.IO.Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
{
var response = reader.ReadToEnd();
}
}

Related

HttpRequest.GetResponse() taking too much time

I have an outlook addin application which I'm connecting with Salesforce.
I'm trying to request some data from SF API which normally returns result in less than 1 second, but with my code It takes from 5-15 seconds to complete.
I have also tried to set proxy to null.
Here is my code:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
if (includeCustomHeader == true)
{
req.Headers.Add("Authorization: OAuth " + ServiceManager.Token.access_token);
req.Headers.Add("X-PrettyPrint:1");
req.ContentType = "application/json";
}
else
{
req.ContentType = "application/x-www-form-urlencoded";
}
req.Method = "POST";
req.Proxy = null;
byte[] data = System.Text.Encoding.ASCII.GetBytes(payload);
req.ContentLength = data.Length;
using (var responseStream = req.GetRequestStream())
{
responseStream.Write(data, 0, data.Length);
}
//here it's taking from 5-15 seconds, each request gets a batch of 200 records
using (var response = req.GetResponse())
{
return new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
}
Don't know what am I missing , or could there be any other reason?
Suggestions?

Method Not Allowed using Cisco REST API

I am trying to change agent state using REST API provided from Cisco.
here is the code that I wrote :
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://url:8445/finesse/api/User/agent2"));
request.Credentials = new NetworkCredential("agent2", "12345");
request.Method = "POST";
request.ContentType = "application/xml";
// request.Accept = "application/xml";
XElement redmineRequestXML =
new XElement("User",
new XElement("state", "READY"),
new XElement("extension", "3010")
);
byte[] bytes = Encoding.UTF8.GetBytes(redmineRequestXML.ToString());
request.ContentLength = bytes.Length;
using (Stream putStream = request.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
// Log the response from Redmine RESTful service
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
MessageBox.Show(reader.ReadToEnd());
}
And I am getting this error :
The remote server returned an error: (405) Method Not Allowed.
so please any idea could help solving this issue ?
after 2 days I figured out that the issue is to replace this line :
request.Method = "POST";
by this line :
request.Method = "PUT";

Get html source from internet meet some issue

I want to fetch a web page to analyze stock information. I use the following sample code to get html data using c#. While it compiles, running it always ends in an error.
The following is my sample code:
string urlAddress = "http://pchome.syspower.com.tw/stock/sto0/ock2/sid2404.html";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 1414;
var requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes("is_check=1"), 0, 10);
requestStream.Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string rawData = sr.ReadToEnd();
sr.Close();
response.Close();
Does anyone know how to solve this issue?
The errors were mostly related to the order of your code and the closing of Stream objects your were still going to use.
Also I recommend to use using where possible to correctly dispose objects.
Use this code:
string rawData;
byte[] bytes = Encoding.UTF8.GetBytes("is_check=1");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
rawData = sr.ReadToEnd();
}
}
}

client to server, server returns error but client thinks success

MVC Application - uploading file from client to server through a stream:
string responseContents = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(message);
request.Method = "POST";
request.ContentType = "text/xml;charset=utf-8";
request.ContentLength = requestBytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default))
{
responseContents = sr.ReadToEnd();
}
}
the problem is if there is an error on the server side, client account cant be found for example (the client account to save the upload to.) the responseContents returns an error:
<?xml version="1.0" encoding="utf-8"?><Result><Value>FAIL</Value><Message>Client Account can't be NULL</Message></Result>
then continues on with the code
Console.WriteLine("Server returns:");
Console.WriteLine(responseContents);
and the client thinks this is a success.
Is there any sort of way to check the responseContents returned xml for the word 'FAIL' so I can throw an error on the client side?
Regards
J

C# Webrequest to Sockets

I have an application that starts multiple threads, and each thread sends requests to a remote server. After profiling, I noticed that the most time is taken in sending & processing the request. This is the function:
private string GetRequest(string url, string postFields)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = proxy;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Host = Constants.URLDomain;
request.KeepAlive = true;
request.Accept = Constants.Accept;
request.ContentType = "application/json";
request.Headers.Add("MyHeader1", "true");
request.Headers.Add("MyHeader2", "header2value");
request.Headers.Add("MyHeader3", "header3value");
request.Method = "POST";
byte[] postBytes = Encoding.UTF8.GetBytes(postFields);
request.ContentLength = postBytes.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(postBytes, 0, postBytes.Length);
}
string text = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream answer = response.GetResponseStream())
using (StreamReader reader = new StreamReader(answer, System.Text.Encoding.UTF8))
{
text = reader.ReadToEnd();
}
}
return text;
}
I was thinking of changing this code to use sockets so I could improve performance. Will there be actually an improvement if I change to sockets, and more importantly, how do will a sockets implementation of the above code look like?

Categories

Resources