How to let Httpwebresponse ignore the 404 error and continue with it? It's easier than looking for exceptions in input as it is very rare when this happens.
I'm assuming you have a line somewhere in your code like:
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Simply replace it with this:
HttpWebResponse response;
try
{
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mysite.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch(WebException ex)
{
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
//Handle 404 Error...
}
}
If you look at the properties of the WebException that gets thrown, you'll see the property Response. Is this what you are looking for?
Related
I'm trying to verify the existence of a Url using HttpWebRequest. I found a few examples that do basically this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return response.StatusCode;
}
However, if the url is indeed broken, it's not returning a response, it's instead throwing an exception.
I modified my code to this:
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return response.StatusCode;
}
}
catch (System.Net.WebException ex)
{
var response = ex.Response as HttpWebResponse;
return response == null ? HttpStatusCode.InternalServerError : response.StatusCode;
}
which seems to finally do what I want.
But I would like to know, why is the request throwing an exception instead of returning the response with a NotFound status code?
Ya this can be quite annoying when web pages use status codes heavily and not all of them are errors. Which can make processing the body quite a pain. Personally I use this extension method for getting the response.
public static class HttpWebResponseExt
{
public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
{
try
{
return (HttpWebResponse)req.GetResponse();
}
catch (WebException we)
{
var resp = we.Response as HttpWebResponse;
if (resp == null)
throw;
return resp;
}
}
}
Why not? They're both valid design options, and HttpWebRequest was just designed to work this way.
Just like #Will, I wrote similar extension method to get the response content in string from WebException.
/// <summary>
/// Reads Response content in string from WebException
/// </summary>
/// <param name="webException"></param>
/// <returns></returns>
public static (HttpStatusCode statusCode, string? responseString) GetResponseStringNoException(this WebException webException)
{
if (webException.Response is HttpWebResponse response)
{
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new(responseStream, Encoding.Default);
string responseContent = streamReader.ReadToEnd();
HttpStatusCode statusCode = response.StatusCode;
streamReader.Close();
responseStream.Close();
response.Close();
return (statusCode, responseContent);
}
else
{
return (HttpStatusCode.InternalServerError, null);
}
}
The above code is non-optimised solution.
I have the following code:
string getCustomerTokenUrl = "someurl?vi=7&vt=" + encryptedToken + "&DPLF=Y";
HttpWebRequest objRequest = System.Net.HttpWebRequest.Create(getCustomerTokenUrl) as HttpWebRequest;
objRequest.AllowAutoRedirect = false;
try
{
HttpWebResponse response = objRequest.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.MovedPermanently)
{
Console.WriteLine(response.Headers["location"]);
}
}
catch (System.Net.WebException ex)
{
Console.WriteLine(ex);
}
When I run the code, I get a value from the location header, however it is missing an expected query string.
What I get:
http://anotherurl.com/api/SSO/autoSWLLoginCT
What I see in the chrome developer tools if I go directly to the url stored in getCustomerTokenUrl (in the response location header):
http://anotherurl.com/api/SSO/autoSWLLoginCT?ct=dabe6dcd25385b7a77e3a1587cef9e6fee20e7af0952a4691ef2169ef9ec6704367626a647c07473ec2b3c98746b79cc66a646857c85930042a616db69442ca5
Is there something I am configuring wrong that would cause the query string to be truncated?
This question already exists:
How to properly catch a 404 error in .NET [duplicate]
Closed 8 years ago.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
request.Method = WebRequestMethods.Http.Head;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
bool pageExists = response.StatusCode == HttpStatusCode.OK;
When the address is an invalid one the software crashes on the 3rd line of the code when its supposed to get response, any way to work around this?
You can get the response like this
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/afakepage");
request.Method = WebRequestMethods.Http.Head;
try
{
using (WebResponse response = request.GetResponse())
{
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
MessageBox.Show(httpRespnse.StatusCode.ToString());
}
}
I'm catching an exception, which I've done in two ways. With the first method, I'm catching the full exception, checking to see if the inner exception is of type WebException, and if it is, obtain the response stream. Below is the first example, however I always get a zero-string response:
catch (Exception e)
{
if (e.InnerException is WebException)
{
WebException webEx = (WebException)e.InnerException;
HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
string response = string.Empty;
if (myResponse != null)
{
StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
response = strm.ReadToEnd();
//EMPTY RESPONSE
}
}
}
However, if I catch the Web Exception, and pretty much do the same thing, I obtain the response fine:
catch (WebException e)
{
HttpWebResponse myResponse = e.Response as HttpWebResponse;
string response = string.Empty;
if (myResponse != null)
{
StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
response = strm.ReadToEnd();
//POPULATED RESPONSE
}
}
Any ideas why I'm able to parse the response in the second example but not in the first?
Don't look at the InnerException, in your second example you're reading the response from the exception you caught, that's why it works. Just change it to this, should work fine:
catch (Exception e)
{
if (e is WebException)
{
WebException webEx = (WebException)e;
HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
string response = string.Empty;
if (myResponse != null)
{
StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
response = strm.ReadToEnd();
}
}
}
Don't check the InnerException, it is the Exception instance that caused the current exception (From MSDN)
Just perform a check on Exception -
catch (Exception e)
{
if (e is WebException)
{
WebException webEx = (WebException)e.InnerException;
HttpWebResponse myResponse = webEx.Response as HttpWebResponse;
string response = string.Empty;
if (myResponse != null)
{
StreamReader strm = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
response = strm.ReadToEnd();
//EMPTY RESPONSE
}
}
}
Hope it helps !!
We have a url and we need to check whether web page is active or not. We tried following code:
WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(URL);
objRequest.Method = "HEAD";
try
{
objResponse = objRequest.GetResponse();
objResponse.Close();
}
catch (Exception ex)
{
}
Above code gave exception if unable to get a response but also works fine even if we have a "server error" on that page? Any help how to get server error?
The HttpResponse class has a StatusCode property which you can check. If it's 200 everything is ok.
You can change your code to this:
HttpWebResponse objResponse = null;
var objRequest = HttpWebRequest.Create("http://google.com");
objResponse = (HttpWebResponse) objRequest.GetResponse();
if(objResponse.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("It failed");
}else{
Console.WriteLine("It worked");
}
For one thing, use a using statement on the response - that way you'll dispose of it whatever happens.
Now, if a WebException is thrown, you can catch that and look at WebException.Response to find out the status code and any data sent back:
WebRequest request = WebRequest.Create(URL);
request.Method = "HEAD";
try
{
using (WebResponse response = request.GetResponse())
{
// Use data for success case
}
}
catch (WebException ex)
{
HttpWebResponse errorResponse = (HttpWebResponse) ex.Response;
HttpStatusCode status = errorResponse.StatusCode;
// etc
}