C# Restful client - connection timeout - c#

I'm using WinForms and accessing my Restful webservice. For some reason the code after a while breaks, by giving the timeout error while connecting to the server.
The problem might also be due to my code design.
Here's my Restful client class
public class Restful
{
public string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("MyUserName:MyPassword"));
public string POST(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create("http://myserverdomain.com/api/webservice/someMethod");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.Method = WebRequestMethods.Http.Post;
request.Headers["Authorization"] = this.auth;
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream postStream = null;
try
{
// ERROR IS IN THIS LINE
postStream = request.GetRequestStream();
}
catch (WebException ex)
{
// I'm kind of creating an hack here..which isn't good..
if (ex.Status.ToString() == "ConnectFailure")
{
System.Threading.Thread.Sleep(1000);
this.POST(parameters);
}
}
if (postStream == null)
return string.Empty;
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
return responseValue;
using (var responseStream = response.GetResponseStream())
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
responseValue = reader.ReadToEnd();
return responseValue;
}
}
}
I'm receiving the error (after a few successfully send items):
Unable to connect to remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond MyServerIpAddress
Sometimes I send thousands of items to the server, sometimes I only send 2 or 4. So I call this POST function within a loop.
try
{
foreach (app.views.Documents doc in DocumentsView)
{
var parameters = "key=" + doc.key;
parameters += "&param1=" + doc.param1 + "&param2=" + doc.param2;
/*
* Validates the response of Restful service.
* The response is always in JSON format.
*/
if (response(Restful.POST(parameters)) == false)
{
MessageBox.Show("Error while sending the ID: " + doc.id.ToString());
break;
};
}
}
catch (Exception ex)
{
MessageBox.Show("Error while sending documents: " + ex.Message);
}

You can change the default timeout of your HttpWebRequest to be some thing larger than the default, for example:
request.Timeout = 120000;
I think the default is 100 seconds.
You can also check this adjusting-httpwebrequest-connection-timeout-in-c-sharp

taking the failure at face value, it says that the remote machine didnt respond. Most likely causes
wrong name or ip address
windows firewall is on on the remote machine

Related

HttpWebRequest.GetRequestStream() connection gets actively refused in executable but not in WPF standalone application

I am working with web server to make calls to its API via HttpWebRequests. I wrote a standalone WPF application for testing purposes and all of my requests were functioning correctly. When I referenced the working project file in my production application it is now returning that the request is being actively refused by the server.
public string Post(string xmlData, Transaction transaction)
{
var result = "";
try
{
var webReq = (HttpWebRequest)WebRequest.Create(BaseUrl);
webReq.Accept = "application/xml";
webReq.ContentType = "application/xml";
webReq.Method = "POST";
webReq.KeepAlive = false;
webReq.Proxy = WebRequest.DefaultWebProxy;
webReq.ProtocolVersion = HttpVersion.Version10;
// If we passed in data to be written to the body of the request add it
if (!string.IsNullOrEmpty(xmlData))
{
webReq.ContentLength = xmlData.Length;
using (var streamWriter = new StreamWriter(webReq.GetRequestStream())) /**CONNECTION REFUSED EXCEPTION HERE**/
{
streamWriter.Write(xmlData);
streamWriter.Flush();
streamWriter.Close();
}
}
else //Otherwise write empty string as body
{
webReq.ContentLength = 0;
var data = "";
using (var streamWriter = new StreamWriter(webReq.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
}
//Attempt to get response from web request, catch exception if there is one
using (var response = (HttpWebResponse)webReq.GetResponse())
{
using (var streamreader =
new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException()))
{
result = streamreader.ReadToEnd();
}
}
return result;
}
catch (WebException e)
{
//Handle web exceptions here
}
catch (Exception e)
{
//Handle other exceptions here
}
}
Has anyone else encountered this problem?
After reviewing your fiddler requests I can say that the reason is probably the IP address difference.
You use 192.168.1.186:44000 first time and 192.168.1.86:44000 second time.

Make http WebRequest work in C#

I want to get a respond from an http website,I have used this code
// Create a new request to the mentioned URL.
WebRequest myWebRequest = WebRequest.Create("http://127.0.0.1:8080/geoserver/NosazMohaseb/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=NosazMohaseb:GParcelLAyer&maxFeatures=50&outputFormat=application%2Fjson&bbox=5727579.437775434,3838435.3419322656,5727581.1322169611,3838437.0363737918");
// var myWebRequest = WebRequest.Create(myUri);
myWebRequest.Method ="GET";
myWebRequest.Timeout = TimeOut;
if (myWebRequest is HttpWebRequest)
{
( myWebRequest as HttpWebRequest).Accept = "application/json";
(myWebRequest as HttpWebRequest).ContentType = "application/json";
//(myWebRequest as HttpWebRequest).Accept =
(myWebRequest as HttpWebRequest).KeepAlive = false;
(myWebRequest as HttpWebRequest).UserAgent = "SharpMap-WMSLayer";
}
if (Credentials != null)
{
myWebRequest.Credentials = Credentials;
myWebRequest.PreAuthenticate = true;
}
else
myWebRequest.Credentials = CredentialCache.DefaultCredentials;
if (Proxy != null)
myWebRequest.Proxy = Proxy;
try
{
using (var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
{
using (var dataStream = myWebResponse.GetResponseStream())
{
var cLength = (int)myWebResponse.ContentLength;
}
myWebResponse.Close();
}
}
catch (WebException webEx)
{
if (!this.ContinueOnError)
throw (new RenderException(
"There was a problem connecting to the WMS server when rendering layer '" + LayerName + "'",
webEx));
}
catch (Exception ex)
{
if (!ContinueOnError)
throw (new RenderException("There was a problem rendering layer '" + LayerName + "'", ex));
}
But when I try to get cLength it is -1,So it does not work,But When I try to access this website
http://127.0.0.1:8080/geoserver/NosazMohaseb/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=NosazMohaseb:GParcelLAyer&maxFeatures=50&outputFormat=application%2Fjson&bbox=5727579.437775434,3838435.3419322656,5727581.1322169611,3838437.0363737918
I get following answer
{"type":"FeatureCollection","totalFeatures":2,"features":[{"type":"Feature","id":"GParcelLAyer.14970","geometry":{"type":"Polygon","coordinates":[[[5727597.96542913,3838442.73401128],[5727595.60003176,3838429.21114233],[5727576.62444883,3838431.10604568],[5727571.16785106,3838432.76483769],[5727569.78420277,3838437.30665986],[5727570.19434939,3838439.63808217],[5727597.96542913,3838442.73401128]]]},"geometry_name":"geom","properties":{"FK_BlockNo":"12055","FK_LandNo":"8","NoApart":"100000","Name":" ","Family":"??","Father":" ","MeliNo":" ","MalekType":"1 ","PostCode":"0 ","Id_Parvande":null,"BuildNo":null,"BuildTypeCode":null,"BuildUserTypeCode":null,"BuildViewTypeCode":null,"BuildGhedmatCode":null,"Farsoode":"0"}}],"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::900913"}}}
So it seems I am missing somthing while getting respond using C#..Can you please help me find my mistake?
thanks
In your code you're actually just getting response stream and later you're not reading anything from this stream - that's why you're not getting any data.
You have to create stream reader and use it to read data from response stream (consider to use buffered Read instead of ReadToEnd if your data size is large):
using (var dataStream = myWebResponse.GetResponseStream())
using (var reader = new StreamReader(dataStream))
{
string data = reader.ReadToEnd();
}
Concerning ContentLength equals to -1 in your case - well, it can be something at your server-side, check if your server actually returns this header. In fact, this header is not mandatory and you should not rely on it.

Error : 413 Request Entity Too Large in C# WinForm Application

I am trying to send JSON Object to Server for data synchronization.
This JSON object contain non-synchronized images and their data.
Real problem is not with he JSON or the Synchronization code.
But it is with the size of the Request i am sending to the server.
if the size cross the limit 1.1MB then i Got this message
The remote server returned an error: (413) Request Entity Too Large.
Please Help me. It is pur C# application not the WCF application.
Domain Hosting provider is Godady.com.
Using Apache server and PHP script.
Every this is working fine for smaller size. but it give exception error when size cross 1.1MB.
Here is My Request Code.
public string SubmitData(string poststring)
{
string result ="false";
if (poststring.ToLower() == "empty")
{
result = "empty";
return result;
}
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = poststring;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://blunor.com/dark/data.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
showMessageBox(data.Length.ToString(), "Message", 1);
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
// this block of code check if response is +ve or negtive..
string res_num = sr.ReadToEnd();
if (res_num == "1")
{
result = "true";
}
else
{
result = "false";
}
//block end here.....
sr.Close();
stream.Close();
return result;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return result;
}
For Server php post_max_size = 128M and Upload_max_filesize = 32M
Please Help......

WebException details changed on VS.Net

A Rest API call throws an exception on post. And that is
The remote server returned an error: (404) Not Found.
The following code calling the api
try
{
RestClient client = new RestClient(...);
string apiResponse = client.MakeRequest(..);
}
catch (WebException wex)
{
throw wex;
}
It works fine when the fiddler is capturing traffic. But if the fiddler is not capturing then client received the following exception.
The remote server returned an error: (502) Bad Gateway.
PS. Postman (Chrome extension) and Soap UI also received 404: Not Found
UPDATED:
This is the code and the error is received while debugging
public string MakeRequest(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create(_RestEndPoint + (parameters ?? String.Empty));
request.Proxy = WebRequest.DefaultWebProxy;
request.ContentLength = 0;
request.Method = _Method.ToString();
request.ContentType = _ContentType;
request.KeepAlive = true;
if (_RequestHeader != null)
{
foreach (var hdr in _RequestHeader)
{
request.Headers.Add(hdr.Key, hdr.Value);
}
}
if (_Method == HttpVerb.POST || _Method == HttpVerb.PUT)
{
if (!string.IsNullOrEmpty(_PayLoad))
{
var bytes = Encoding.UTF8.GetBytes(_PayLoad);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
}
}
using (var response = (HttpWebResponse)request.GetResponse())//Error returns here
{
var responseValue = string.Empty;
checkForResponseExceptions(response.StatusCode, parameters);
// grab the response
using (var responseStream = request.GetResponse().GetResponseStream())
{
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
}
return responseValue;
}
}
Can anyone please point out what am i missing?
Update 2:
I have tried the following code and have the same issue
if (_Method == HttpVerb.POST)
{
using (var wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = _ContentType;
foreach (var hdr in _RequestHeader)
{
wb.Headers.Add(hdr.Key, hdr.Value);
}
try
{
var response = wb.UploadString(_RestEndPoint + (parameters ?? String.Empty), _Method.ToString(), _PayLoad);
}
catch (Exception ex)
{
throw ex;
}
}
}
So, I guess something is wrong in the network settings as #GSerg commented on Dec 4 at 10:01. But there are no proxy set up in connection tab of IE settings. What and how should i check to get rid of this problem??
HTTP errors are grouped by "type of errors"
4xx errors are "client" errors, errors that are linked to the user doing a mistake, like 404 is the client asking for something that does not exist on the server.
5xx errors are "server" errors, meaning that the server had a problem answering the request, because of internal issues.
The 502 bad gateway is usually sent from a server when he couldn't get a request from another server. In your case, it could be coming from fiddler, because you're probably still making the query to fiddler who is stopped, and thus cannot answer.

HttpWebRequest: Unable to connect to the remote server

I develop client app which connects to the server and fetches different information from it. It is multithreaded app. When I start it with a few threads it works perfect.
Until it start throwing an exception with the following message:
"Unable to connect to the remote server"
I've used TCPView and cannot find anything about my client app. So when it starts returning "Unable to Connect" it doesn't even OPEN any http connections...
How can I figure out why it doesn't open connection?
Thanks,
EDIT:
Here is the code I'm using in Multiple threads to fecth page content:
HttpWebResponse response = null;
Stream resStream = null;
StreamReader reader = null;
string res = "";
try
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(requestUrl);
if (cookies_ == null)
{
cookies_ = new CookieContainer();
}
request.Timeout = timeoutVal_;
request.ReadWriteTimeout = timeoutVal_ * 2;
request.KeepAlive = false;
if (bUseCookies)
{
request.CookieContainer = cookies_;
}
// execute the request
response = (HttpWebResponse)
request.GetResponse();
resStream = response.GetResponseStream();
reader = new StreamReader(resStream);
res = reader.ReadToEnd();
}
catch (Exception ex)
{
throw new Exception(siteToken + " " + ex.Message);
}
finally
{
if (response != null)
response.Close();
if (resStream != null)
resStream.Close();
if (reader != null)
{
reader.Close();
}
}
return res;
After a couple minutes threads getting into cycle with Timeout Exception or Unable to connect to Server.
The strange thing that if I start Fiddler, connections get reactivated and threads continue working for some time. How does Fiddler fix that problem?
You may be connecting internet through a proxy check your IE lan settings. from c# you need to add proxy settings.
var request = (HttpWebRequest)WebRequest.CreateHttp(url);
WebProxy proxy = new WebProxy("http://127.0.0.1:8888", true);
proxy.Credentials = new NetworkCredential("user", "pwd", "ADomain");
request.Proxy = proxy;
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
request.Timeout = 1000 * 60 * 5;
request.Method = method;
request.Headers.Add("DAUTH", dauth);request.GetResponse();

Categories

Resources