ASP.NET Get Web Response when HTTP Status is NOT 200 OK - c#

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

Related

Getting 400 exception in HttpWebRequest Call

I am using Postman to get the response from rest end point, and if I pass wrong data I am getting 400 exception which is very correct as per the logic.
But if I try to call the same web request from C# code(with same wrong parameter), I am getting exception but not the same as I am getting in Postman tool.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apiurl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = ".Net application";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(obj);//obj is parameter
streamWriter.Write(json);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
}
Can I know why I am getting errors differently from postman and C# code
Regards
Anand
Added below code in the exception block and it gave me the same response as Postman
catch(WebException ex)
{
string message = ex.Message;
WebResponse errorResponse = ex.Response;
if (errorResponse != null)
{
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
message = reader.ReadToEnd();
}
}
}

c# HttpWebResponse response null instead of 504

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.

How to manage client and server error?

I have this code:
public static string Connect(string Uri)
{
try
{
HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
connection.Method = "GET";
string response;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
responseText = responseStream.ReadToEnd();
}
return response;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
If the API return 200 http status the response variable is returned correctly, instead if I have client error 400 or 500 the code fall in exception. I want manage this exception in the try instead fall in the Console.WriteLine, there is a change for do this?
You could do something like this, to minimise duplicated code and handle the exception as close to where it's thrown as possible.
public static string Connect(string Uri)
{
HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
connection.Method = "GET";
string response;
HttpWebResponse response = null;
try
{
response = request.GetResponse() as HttpWebResponse
}
catch (WebException ex)
{
response = ex.Response;
}
using (response)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
responseText = responseStream.ReadToEnd();
}
return response;
}

Get http status return ObjectDisposedException

I'm trying to get the status code returned from http response, like this:
try
{
HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
string text
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
text = responseStream.ReadToEnd();
}
var responseHeader = (HttpWebResponse)request.GetResponse();
var status = responseHeader.StatusCode;
}
catch (WebException ex)
{
MessageBox.Show(ex.ToString());
}
the problem is that I get this exception:
System.ObjectDisposedException : "Cannot access to removed object Name: 'System.Net.HttpWebResponse'."}
on this line: var status = responseHeader.StatusCode;
why happean this? I want get the status code and the description
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
will dispose the response after leaving the using block.
So another call to (HttpWebResponse)request.GetResponse(); will throw the exception. Additionally, because it's a web response, you cannot read it twice.
Try this alternative:
HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
string text;
HttpStatusCode status;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
text = responseStream.ReadToEnd();
status = response.StatusCode;
}

How to handle json from http

I use a WebClient class to nagivate to a website. it returns me a download dialog box to download the output in a json file. Issit possible to read whats in the json file without downloading it? i opened up chrome and pasted the same url and chrome showed me the output in the browser itself.
It depends on the content type and browser, content may be zipped in some instances. Stackoverflow API is one such example.
In these cases you need to set request.AutomaticDecompression. Below code might give you fair idea of understanding and to continue from there.
public string CallRequest(Uri url)
{
var request = WebRequest.Create(url) as HttpWebRequest;
var httpResponse = "";
if (request != null)
{
request.UserAgent = "stackoverflow"; // just example.
request.Accept = "gzip,deflate";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
httpResponse = reader.ReadToEnd();
}
}
}
return httpResponse;
}
Just make a request to the link and you will have the JSON in a string:
public static Response MakeRequest(string requestUrl){
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
Response jsonResponse
= objResponse as Response;
return jsonResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}

Categories