Im setting up a project on a new dev machine. (Win7, vs2k12)
The code works fine on the production machine.
This code gives me "The operation has timed out".
var request = (HttpWebRequest) System.Net.WebRequest.Create(url);
request.Timeout = TimeoutMilliSeconds;
request.Method = "GET";
request.UserAgent = "X";
var response = (HttpWebResponse)request.GetResponse();
The url works fine when I call it from the browser.
I know which ports are open for incoming traffic.
Im using IIS express.
How do I proceed?
Thanks
Set the ReadWriteTimeout property.For details see a link:
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout.aspx
request.ReadWriteTimeout = 5000; //Increase Time as your requirement.
Related
We are sending JsonConvert.SerializeObject(lstobject); to the URL here. lstobject is a large list sent to the url.error also returned after 3 minutes to log error how to make webrequest to wait 5 minutes.
var httpWebRequest = (HttpWebRequest)WebRequest
.Create(ConfigurationManager.AppSettings["JsonPayloadPostUrl"]
.ToString());
httpWebRequest.Timeout = 1000000;
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonPayload);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
Ee have used httpWebRequest.Timeout = 1000000; but the server is unable to send request back in less than 5 minutes. How to make request to wait for server for response ?
I might be missing something reading your question, but HTTP 500 server error means that the server has provided a response, saying it encountered some internal issue. So you cannot prevent it by setting a bigger timeout on the Request side.
Following https://www.w3.org/Protocols/HTTP/HTRESP.html
Internal Error 500
The server encountered an unexpected condition which prevented it from
fulfilling the request.
I would say either your request is not properly built, or the server has some application-side issue.
Coming back to the timeout setting way, I think it looks properly. Please note that this time might be taking into account topics like DNS name resolution etc. which in turn might require a bit more time than it seems in the first place. This shouldn't be a problem in your case though, looking at the value you are trying to set.
I am totally new to WebApi and WebRequests and other things.
After hours of googling, finally, I managed to do POST using C# and HttpWebRequest.
When I do HttpWebRequest in debug mode using Visual Studio I do not get any exceptions.
My app work as I accept , I get data to webApi server and also get back data.
To be sure how my app communicate with WebApi server I start Fiddler Web Debugger.
During the POST to WebApi, Fiddler chace 401 errors
{"Message":"Authorization has been denied for this request."}
Steping step by step in debuger I fund that following lines of code doing 401 error
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Credentials = new NetworkCredential(username, password);
wr.Method = "POST";
wr.ContentType = "application/json";
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(body);
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length); //After this line of code Fidler Chace HTTP 401
}
Later in code when I do wr.GetResponse() I do get status 200OK.
My questions are :
Do I need to redesign my code to avoid this error in Fiddler ?
Is there other methods to fill HttpWebRequest whit jsonSting beside using GetRequestStream() ?
If your service is enabled with Windows Authentcation, then in Fiddler, you can select the option to automatically authenticate using your logged on credentials by going here:
Composer tab -> Options tab -> Automatically Authenticate
Also, why not use HttpClient from System.Net.Http?...It has a much better and easy programming model...example:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9095/");
HttpResponseMessage response = client.PostAsJsonAsync<Customer>("api/values", cust).Result;
In the application I am currently working on there is a backend java app that is caching a bunch of data. The asp.net part is allowing users to update database tables. Each time the DB is updated the cache in the java application should be cleared. So basically I have a list of 4 URLs that each need to be hit in order to clear the cache. My basic solution was to loop through each url and create a HttpWebRequest and get then get the response. So basically I have this for each request:
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = 0;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseString = readStream.ReadToEnd();
returnList.Add(string.Format("Refresh response from {0}.<br />{1}", url, responseString));
readStream.Close();
receiveStream.Close();
}
On my local machine everything works great. But when I deploy to our development server it just hangs and does nothing. If I remove request.ContentLength = 0; then the remote server throws a 411: Length expected error.
I am really stuck here and any help would be greatly appreciated.
Either a solution to the HttpWebRequest problem I am having or a different solution to calling each URL would work, I'm not picky.
Thanks in advance.
Why are using request.method as "POST"? Are you posting any data, if not try removing both content length and request method.
Pretty sure this was a network issue. I tried hitting a different url (the load balancer) and had no problems so the java guys are making a changes so I can just hit the load balancer and whatever server the request ends up on will make sure all servers caches are cleared.
The code that is working:
var request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseString = readStream.ReadToEnd();
returnString = string.Format(#"Refresh response from<br />{0}{1}", url, responseString);
readStream.Close();
receiveStream.Close();
}
I am truing to integrate fusemail in asp.net 2.0. I am using HttpWebRequest for requesting the API pages. It has recently come to my notice that HttpWebRequest fails the first time and then continues and subsequent requests succeed.
say ( i know if i use goto it is a bad programming approach) if i use this code
retry:
try
{
Uri uri = new Uri("http://www.fusemail.com/api/request.html");
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.PreAuthenticate = true;
request.Method =
WebRequestMethods.Http.Post;
//request.ReadWriteTimeout = System.Threading.Timeout.Infinite;
//request.Timeout = System.Threading.Timeout.Infinite;
request.ContentLength = data.Length;
request.ContentType =
"application/x-www-form-urlencoded";
//request.UserAgent = Request.UserAgent;
request.UserAgent = "Mozilla/4.0";
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = true;
//request.Accept = "Accept: text/html,application/xhtml+xml,application/xml";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
//Response.Write(tmp);
if (!String.IsNullOrEmpty(tmp))
{
return tmp;
}
}
return String.Empty;
}
catch (WebException ex)
{
goto retry;
}
it works after failing once. i am writing to a text file in case of an error and after i failed request it works the second time. I am using ASP.Net 2.0 and the website is hosted on IIS 7 with Windows Server 2008 Standard. Also pinging the API address it fails the first time and then responds
C:\>ping 67.207.202.118
Pinging 67.207.202.118 with 32 bytes of data:
Reply from 192.168.0.253: **Destination host unreachable**.
Reply from 67.207.202.118: bytes=32 time=218ms TTL=49
Reply from 67.207.202.118: bytes=32 time=218ms TTL=49
Reply from 67.207.202.118: bytes=32 time=217ms TTL=49
Ping statistics for 67.207.202.118:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 217ms, Maximum = 218ms, Average = 217ms
The first time it fails in HttpWebRequest it fails with this error
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: 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 67.207.202.118:80
Is there an authentication issue the first time?. i read on some forums it first sends a 401 Unauthorized and then it can connect. I am unable to verify this using Fiddler.
Is there anything wrong with IIS configuration?
This is not a programming issue at all, I have faced a similar problem later and it was a network configuration problem due to ISA server / Firewall settings.
You have to contact your network administrator to check this issue.
I wish this helped you.
Yours,
Mohamed Kamal Elbeah
Senior .Net Developer
I recently came by this same issue. The solution in my case involved my testing environment, since I had multiple Ethernet adapters connected to my computer. While you may have a different IP for each of your Ethernet adapters, if they are all assigned to the same subnet this may cause a problem. The TCP connection is only attempted using one NIC at a time. So in my case, on the first try it would attempt the connection on one adapter that was not connected to my remote host, then on the second try it would connect using the second adapter which was connected. - Hope this helps someone.
swf file in https zone, upload script in http zone.
File upload fine in ie, and not work on firefox, opera.
this code:
request.url = this.main.serverHostUpload + "/upload_web.php";
request.method = URLRequestMethod.POST;
request.contentType = "multipart/form-data; boundary=" + UploadPostHelper.getBoundary();
request.data = new URLVariables();
request.data.dst_file = fileDstName;
request.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
var fr:FileReference = this.main.photos[this.iLoadPh].fr;
fr.cancel();
fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,createOrderStep6Res);
fr.upload(request,"file");
I have had similar problems and sometimes it is the quality of the cert if you are posting over https. You also should make sure that fileference is calling a URL with the actual port number (443 for https).
I have also seen fire reference reconnect in browsers other than IE. You can spot this using something like Tamper Data for Firefox or Fiddler to get a NIC-level view of it.