How to manage client and server error? - c#

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

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# Post-Request Status 400 Bad Request

I am currently working on a C# Programm that is supposed to get Data from a REST API that I host.
The API requires a token for authentication which is returned from a POST request.
When I try to do the POST with C# I get a bad request (Status 400) but the GET request works fine. Now, My question is what I did wrong or what might be the cause for that error. When doing the request with postman both work perfectly.
The POST function:
void POST(string url, string jsonContent) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
Console.WriteLine(response);
}
} catch (WebException ex) {
Console.WriteLine(ex);
}
}
The GET function:
string GET(string url) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}

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

why I am getting object not set to instance when i call webrequest.create with a uri that does not exist

I am testing out a browser am creating,
if i send a uri that exists to webrequest, everything is find,
but i get an object not set to instance when i send a uri that does not exist
such a http://www.bgdygjhcu.com
I expect the method to throw a not found exception. here is the method call
String stream = await Task.Run(() => web.Navigate("http://www.yahoo2gh.com"));
and here is the method that does the work
public async Task<String> Navigate(string uri)
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(uri);
try
{
using (WebResponse response = request.GetResponse())
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
//Set StatusCode
StatusCode = httpResponse.StatusCode.ToString();
//Create Stream
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}
catch (WebException exception)
{
using (HttpWebResponse response = (HttpWebResponse)exception.Response)
{
// HttpWebResponse httpResponse = (HttpWebResponse)response;
StatusCodeInteger = (int)response.StatusCode;
//return httpResponse;
return "empty";// response.StatusCode.ToString();
}
}
}

Categories