An unexpected error occurred on a receive. WebRequest already overriden - c#

I never thought I have to ask a question here, but I am at my wit's end.
We try contact a server and receive XML Data via SOAP from there. Regulary it's running fine, but sometimes and without any hint why, we've got the the following error:
Translated from german:
The underlying connection was closed: An unexpected error occurred on a
receive.
So I looked for possible reasons. And I overrode the WebRequest Method.
public class MyHttpClientProtocol : SoapHttpClientProtocol
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
//Setting KeepAlive to false
webRequest.KeepAlive = false;
return webRequest;
}
}
First of all? - Is this correct or did I chose the wrong base class?
I am not sure at all, but I use SoapHttpClientProtocoll in my service, but in the Request Header (used Fiddler) the "Connection" stills "keep-alive".
The error is rare but it occours and if it does, it does it for a longer time.
So I tried to debug the problem. And if I do and I've got the error he repeats to try the delegate:
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
I can't jump in. VS 2010 does not support it.
I am working with X509Certificate2.
Please give me an idea.. I can't see the solution.

Related

WebRequest - GetRequestStream timing out with exception

I'm writing this short module where I have to modify an addressed resource with a PUT method. I'm using the WebRequest class to make this URI request and the GetRequestStream() to get the stream to write to.
However, it seems that after a couple of successful method calls (and using the PUT to modify resources) via this method below, my application hangs and then throws a WebException: The request timed out. error. Here's what the code looks like:
public void SendOffMessageToResource(int res_ID){
var httpWebRequest = WebRequest.Create ("http://192.168.x.x/api/sample_user/resources/1/state");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) //here's where the VS seems to take a long long time to step over to the next line when the error happens.
{
string json = "{\"on\":false}";
streamWriter.Write(json);
streamWriter.Close();
}
}
I am already disposing the StreamWriter. I'm not even using the GetResponse() method, because all I need to do on this URI is actually modify the addressed resource with PUT method. I am not sure why it still throws an error and hangs the application. The search of previous threads only revealed that people should be using using statements to dispose resources, but I'm already doing that I think or perhaps I'm missing something? Do I always need to use GetResponse() to complete the request and dispose that always in addition to this?
Do I always need to use GetResponse() to complete the request and dispose that always in addition to this?
Yes, just that.

Http Get Request GetResponse Error

Im trying to send a get request and get the content of a webpage. i have these code.
string url = "www.google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)response.GetResponse();
I found these codes from many site and it is correct but "GetResponse" is giving error. Its explanation below.
Is it a problem of Visual Studio 2012 ? It cant find GetResponse method and just find GetResponseStream method when I press G.
I tried to do this with WebClient class but WebClient cannot be found also.
Do these problems occur because of Visual Studio 2012? or any reason ?
Error 1 'System.Net.HttpWebResponse' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebResponse' could be found (are you missing a using directive or an assembly reference?) C:\Users\abidinberkay1\documents\visual studio 2012\Projects\App1\App1\BlankPage1.xaml.cs 45 66 App1
You're calling "response.GetResponse()." It's request.GetResponse().
Update: Based on your comments, I'll propose some new code:
private async void btnRequest_Click(object sender, EventArgs e) // Note: async added
{
string url = "www.google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); // (note: await added, method call changed to GetResponseAsync()
}
I've updated your code to use the C# 5.0 async and await pattern. This allows you to easily use asynchronous methods while writing code that feels synchronous. In order to do this, I've added the async keyword to the method declaration, prior to the return type (void in this case), and I've added the await keyword prior to calling WebRequest.GetResponseAsync().
To answer your question regarding how to know which library you're using: in this case, you chose a Windows Store app. You should specifically call out what kind of project you're working on - it'll help us nail these kinds of things down faster.

POST data to WCF Service from WP7

I am working on a WP7 application. If an error happens, I want to log the error back to my server. To handle this, I have created a WCF service operation. I want this operation to be REST ful so that I can later use it with iPhone and Android apps. Because I'm writing information to the database, I thought the POST method would be best. For this reason, I'm using WebInvoke. To do this, I'm using the following code:
[OperationContract]
[WebInvoke(UriTemplate = "/LogError/{message}/{stackTrace}", ResponseFormat = WebMessageFormat.Json)]
public void LogError(string message, string stackTrace)
{
// Write info to the database
}
From my WP7 app, I want to call this operaiton via a WebClient. My question is, how do I do that? I don't understand how to call the LogError operation and pass along the required data via the WebClient.
Thank you for your help!
If I am getting your Service method correctly, that method is not a POST method. You can just call that with a WebClient
WebClient wc = new WebClient()
Uri uri = new Uri("http://yourUri/LogError/ABC/XYZ"); //ABC is your message and XYZ is your stacktrace string.
wc.DownloadStringAsync(uri);
Or if you are thinking about real HTTP 'POST' then below might help.
You can use HttpWebRequest to do a POST on to any service which is accepting POST
This link may be helpful - WCF REST POST XML - The remote server returned an error: (400) Bad Request
Something along the lines:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://serveraddress/LogError/{message}/{stackTrace}");
If you would want to send additional information later on, you can do so with:
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ExecuteAction), request);
And have a callback:
void ExecuteAction(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
using (Stream s = request.EndGetRequestStream(result))
{
s.Write(data, 0, data.Length);
}
}
If there is a specific string response from the service, you might as well include the data in the WebClient and use DownloadStringAsync to get the response data.
For starters, I found a website that should help you get started with calling the service from WP7.
Try this and let me know what you think
Have a look at this post http://blog.ike.to/2011/02/02/wp7-application-crash-reporter/
It sounds like it will pretty much do what you need already, although you might want to tweak it to suit your own service interface.

WebException in getResponse()

here my code-
private string HttpContent(string url)
{
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
string result = sr.ReadToEnd();
sr.Close();
return result;
}
exception comes in 2nd line in objRequest.GetResponse(). If I open it quick watch window I get:
'objRequest.GetResponse()' threw an exception of type 'System.Net.WebException'
"The remote server returned an error:(404) Not Found."
That seems pretty self-explanatory, really; Check your URL to make sure you're hitting the right location, or make sure that your target server is actually running.
It says what it says:
The remote server returned an error:(404) Not Found.
Your URL does not exist on the server and is not recognised. Your client code is not optimal but should work.
This error message is as it declares, the URL that you requested came back as a 404 error meaning that the page was not found.
Now it is possible that they are doing some odd "redirect" so you might try setting
objRequest.AllowAutoRedirect = true;
and see if that helps. However based on the 404 rather than a 301 or 302 response I'm not sure it will make any difference.
Try to call Url from your browser, if you get response you will be sure that your Url is working. Maybe in your computer there is proxy, you have pass proxy in your code.
That may help you
the problem is that the path [url] is incorrect you pass to method().
the URL may be not well form or check the url that 's work or not. if you not sure that's should always correct then you can use try catch if you want.

.NET HttpWebRequest HTTPS Error

Hello I'm trying to fetch data from a https web (i'm not behind firewall or proxy) however even accepting all certificates it keeps throwing System.Net.WebExceptionStatus.SecureChannelFailure with the message shown: Cancelled the request: Unable to create a secure SSL/TLS channel
... i've looked everywhere so you guys are my last chance.
static void Main(string[] args)
{
RemoteCertificateValidationCallback ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://miyoigo.yoigo.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.Write(reader.ReadToEnd());
}
}
Thanks in advance ;)
try printing the InnerException property of the WebException, should provide a particular reason the negot failed
Console.WriteLine("Inner Exception");
Console.WriteLine(String.Concat(e.InnerException.StackTrace, e.InnerException.Message));
That code works fine for me exactly as you have it. My guess is that you've got something network related going on. Are you behind a proxy or firewall? Like Ray said in his comment, try hitting that URL from a browser.
I have resolved my problem looking at:
How do you get a System.Web.HttpWebRequest object to use SSL 2.0?

Categories