I want to discover what causes a link to not work. Instead of not working, the link should show a particular message, like 404 or 403. How can I discover what HTTP status caused a given request to fail?
if (!IsLinkWorking(link))
{
//Here you can show the error. You don't specify how you want to show it.
TextBox2.ForeColor = System.Drawing.Color.Green;
TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
TextBox2.Text += string.Format("{0}\n working\n\n", link);
}
You need to use an HttpWebRequest. This will return you an HttpWebResponse, that has a StatusCode property - see the documentation here.
Here is an example:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK) {
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
There could be many reasons for not working links, you can try WebClient or HttpWebRequest / HttpWebResponse with proper HTTP header values to check whether link works or not.
Note that in case of 403, 404 etc. errors it throws exception which you should handle or else it will not give you the response status:
try{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
/* Set HTTP header values */
request.Method = "MethodYouWantToUse"; // GET, POST etc.
request.UserAgent = "SomeUserAgent";
// Other header values here...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
catch(WebException wex){
if(wex.Response != null){
HttpWebResponse response = wex.Response as HttpWebResponse;
if (response.StatusCode != HttpStatusCode.OK) {
TextBox2.Text = "HTTP Response is: {0}", response.StatusDescription);
}
}
}
Related
I am writing some tests to ensure I am receiving a 200 status, even if no data is present. I am able to connect to the backend with my testing, but don't know how to read the data and then use the data in an Assert statement to confirm the status code is 200.
public void DataControllerTest_NoData(long dataId)
{
var uri = "http://localhost:8311/api/Data?columnId=";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + dataId);
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
try
{
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
}
catch (WebException we)
{
statusCode = ((HttpWebResponse)we.Response).StatusCode.ToString();
}
Assert.AreEqual(HttpStatusCode.OK, statusCode);
response.Close();
}
As I understand it, you want to find the status code if you see an error by adjusting your code with a small correction as shown below.
public void DataControllerTest_NoData(long dataId)
{
var uri = "http://localhost:8311/api/Data?columnId=";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + dataId);
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = "GET";
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
}
catch (WebException we)
{
statusCode = ((HttpWebResponse)we.Response).StatusCode.ToString();
}
Assert.AreEqual(HttpStatusCode.OK, statusCode);
}
If you want to find the code of the exception text, use the following code
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response = (HttpWebResponse)request.GetResponse();
statusCode = response.StatusCode.ToString();
response.Close();
}
catch (WebException we)
{
string resultError = we.Message;
}
the catch is supposed to give me a 504 but for someone reason, I get a null on:
response = (HttpWebResponse)e.Response;
Below is my code:
var url = "http://www.go435345ogle.com";
HttpWebResponse response = null;
HttpStatusCode statusCode;
get http response
get status
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
//HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(keys.Value.Substring(0, keys.Key.Length - 1));
// Sends the HttpWebRequest and waits for a response.
response = (HttpWebResponse)myHttpWebRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("\r\nWebException Raised. The following error occured : {0}", e.Status);
response = (HttpWebResponse)e.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var sResponse = reader.ReadToEnd();
// Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
}
This is expected behaviour. Since domain www.go435345ogle.com doesn't exist, there is no server you could send request to, and therefore no response to receive. So WebException.Response simply returns null. Microsoft's docs clearly states, that WebException.Response returns:
If a response is available from the Internet resource, a WebResponse
instance that contains the error response from an Internet resource;
otherwise, null.
I am trying to get a response from google in c# to get a token.
I am using the url - https://accounts.google.com/o/oauth2/token.
My code is the following;
public WebResponse GetResponse(string url, params GoogleParameter[] parameters)
{
//Format the parameters
string formattedParameters = string.Empty;
foreach (var par in parameters)
formattedParameters += string.Format("{0}={1}&", par.Name, par.Value);
formattedParameters = formattedParameters.TrimEnd('&');
//Create a request with or without parameters
HttpWebRequest request = null;
if (formattedParameters.Length > 0)
{
//string debug = (string.Format("{0}?{1}", url, formattedParameters));
request = (HttpWebRequest)WebRequest.Create(string.Format("{0}?{1}", url, formattedParameters));
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//Add the authentication header.
request.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
HttpWebResponse response = null;
//Get the response, validate and return
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
if (response == null)
throw new Exception("No Response from Google");
else if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("Incorrect Response: " + response.StatusCode + " " + response.StatusDescription);
return response;
}
The line
response = (HttpWebResponse)request.GetResponse();
is giving me the 405 Error Method Not Allowed.
I have tried for the past two days to fix this but nothing, can anyone see where I have went wrong?
Thanks
Here is code I use to POST into RESTful web service. My problem is with a last line.
For example, my server can reply with different messages and same code.
Now, unless I get 200 OK I just get exception on last line.
I'd like to have better access to response header, etc no matter what code I got. How is that possible?
var request = WebRequest.Create(Options.DitatServerUri + Options.DitatAccountId + "/integration/trip") as HttpWebRequest;
if (request == null) return false;
request.ContentType = "application/json";
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Options.DitatLoginName + ":" + Options.DitatPassword)));
request.Method = "POST";
var serializer = new JavaScriptSerializer();
var serializedData = serializer.Serialize(trip);
var bytes = Encoding.UTF8.GetBytes(serializedData);
request.ContentLength = bytes.Length;
var os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
var response = request.GetResponse();
Example: I get WebException "Invalid Operation" but server actually send message with error explanation.
Building on what Jon said above in the comments, the exception thrown for a bad status code is most likely a WebException, which has Response and Status properties, as per this MSDN page. Therefore, you can get the response via:
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
Why not catch the exception and handle it appropriately?
try
{
var response = request.GetResponse();
}
catch (WebException webEx)
{
Console.WriteLine("Error: {0}", ((HttpWebResponse)webEx.Response).StatusDescription);
}
I need to read the response from an HTTP GET in situations where the Response Status code is not 200 OK. Sometimes it is 401, other 403, however there will be a Response content. If I try to use the HttpWebResponse and HttpWebRequest classes, it throws an exception when the response status is not 200 OK. Any suggestions?
var request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/1");
try
{
using (WebResponse response = request.GetResponse())
{
// Success
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (var streamReader = new StreamReader(response.GetResponseStream()))
Console.WriteLine(streamReader.ReadToEnd());
}
}