Get http status return ObjectDisposedException - c#

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

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

How to view the body returned by an http 500 from a System.Net.HttpWebRequest

I've got a web service that returns an http 500 with some diagnostic information in the body of the response.
I'm doing something like
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch {
//try to view the Request.GetResponse() body here.
}
Since _Request.GetResponse() is returning an http 500 there doesn't seem to be a way to view the response body. According to HTTP 500 Response with Body? this was a known issue in Java 9 years ago. I'm wondering if there's a way to do it in .NET today.
The microsoft docs give a good run down of what HttpWebRequest.GetResponse returns if it fails, you can check it out here https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=netframework-4.8
In your example I believe you need to check for WebException and handle it.
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch (WebException w)
{
//here you can check the reason for the web exception
WebResponse res = w.Response;
using (Stream s = res.GetResponseStream())
{
StreamReader r= new StreamReader(s);
string exceptionMessage = r.ReadToEnd(); //here is your error info
}
}
catch {
//any other exception
}

HttpWebResponse timeout

I am getting timeout exception on code bellow. Only this site is problematic. What is the problem?
string ackoURL = "https://www.zomato.com/sk/brno/u-heligonky-z%C3%A1brdovice-brno-st%C5%99ed/denn%C3%A9-menu";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ackoURL);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
//this code is never executed
}
I tried modifying SecurityProtocol, KeepAlive and simmilar things. Without success.
it waiting these headers
..and it worked
Uri u = new Uri("https://www.zomato.com/sk/brno/u-heligonky-z%C3%A1brdovice-brno-st%C5%99ed/denn%C3%A9-menu");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(u);
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Headers.Add("Accept-Language", "en-gb,en;q=0.5");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using(Stream stream = response.GetResponseStream())
{
using(StreamReader reader= new StreamReader(stream))
{
var result = reader.ReadToEnd();
}
}
}

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

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