HttpWebRequest: Unable to connect to the remote server - c#

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

Related

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.

C# Restful client - connection timeout

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

The remote server returned an error: (404) Not Found. when doing a HttpWebResponse

I am having an issue with my code as I have to verify the status of some websites in order to notify if they are working or not. I can successfully check this for a number of websites, however for a particular one it is always returning 404 Not Found, even though the site is up and I can view it if I try to open the page on the browser, this is my code:
public HttpStatusCode GetHeaders(string url, bool proxyNeeded)
{
HttpStatusCode result = default(HttpStatusCode);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = new NetworkCredential(username, password, domain);
if (proxyNeeded)
{
IWebProxy proxy = new WebProxy("127.0.0.1", port_number);
proxy.Credentials = new NetworkCredential(username, password, domain);
request.Proxy = proxy;
}
try
{
var response = (HttpWebResponse) request.GetResponse();
result = response.StatusCode;
response.Close();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
//TODO: capture the exception!!
}
}
}
return result;
}
The exception does not tell me anything different than "Not Found" which really confuses me as I don't know where else to look.The URL failing is: http://cbprod-app/InterAction/home
If I request the page without setting the proxy, comes back with an "401 Not authorized" as it requires the proxy authentication to be displayed, I am running out of ideas, any suggestion about what am I doing wrong?
Thank you very much in advance.

Remote Server returned an error: (407) Proxy Authentication Required

I am trying to open a url from my winforms application and i am getting "407 Proxy Authentication Required" error. I am able to open a sample application that was deployed on IIS in my machine. but if i try to access any other URL getting this error.
Here is the source code. Any suggestions please.
string url = "http://google.co.in";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
MessageBox.Show(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
That would indicate that the proxy set in your system settings requires you to log in before you're able to use it. If it works in your browser, you've most likely done so in the past. Either disable the proxy in your system's network settings, or add the appropriate headers to authenticate against the proxy.
Try this, it worked for me
string url = "http://google.co.in";
IWebProxy proxy = new WebProxy("your proxy server address", port number ); // port number is of type integer
proxy.Credentials = new NetworkCredential("your user name", "your password");
try
{
WebClient client = new WebClient();
client.Proxy = proxy;
string resp = client.DownloadString(url);
// more processing code
}
}
}
catch (WebException ex)
{
MessageBox.Show(ex.ToString());
}
}
IWebProxy proxy = new WebProxy("proxy address", port number);
proxy.Credentials = new NetworkCredential("username", "password");
using (var webClient = new System.Net.WebClient())
{
webClient.Proxy = proxy;
webClient.DownloadString("url");
}

Webrequest.GetResponse() works on development machine, not on client machines

I tried using WebRequest.GetResponse() on my developement machine(XP) and it works properly and I can read the response stream from the URL, but the compiled code fails on two client machines(Windows 7) when the URL is identical. The WebException.Status is "The network request is not supported." Why would that occur whan trying to access the same URL? The WebException is fired by the GetResponse method. In the catch clause, the response object and the WebException.Response objects are both null. What can I do to further diagnose the problem?
WebRequest request = null;
HttpWebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
String responseFromServer = string.Empty;
string http = string.Empty;
int timeOut = 30000;
string errorMsg = string.Empty;
http = this.URLstring;
bool error = false;
try
{
request = System.Net.WebRequest.Create(http);
request.Timeout = timeOut;
response = (System.Net.HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException wex)
{
error = true;
errorMsg = wex.Message + " " + wex.Status.ToString();
if (wex.Response != null)
{
WebHeaderCollection hdrs = wex.Response.Headers;
for (int i = 0; i < hdrs.Count; i++)
errorMsg += Environment.NewLine + hdrs.Keys[i] + ", " + hdrs[i];
}
}
// Code to read the response stream goes here. it works on development machine.
It could be a privileges matter. To test that, run the App under Win7 'As Administrator'

Categories

Resources