c# HttpWebResponse response null instead of 504 - c#

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.

Related

Reading http page with error http 500 error: incomplete result

I try to read a web page that always throws a http 500 internal server error. When accessing it with firefox or internet explorer I got the full page (~200KB). When I read it with my program, I only got a part of the page (~64KB). This is my code:
try
{
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create("http:// ... ");
request.Timeout = 30000;
request.Method = "GET";
responseContent = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
responseContent = responseReader.ReadToEnd();
}
catch (WebException ex)
{
Stream responseStream = ex.Response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
responseContent = responseReader.ReadToEnd();
}
When I check the traffic with fiddler, I see that Http 500 is returned when accessing the page with the browser and with my program. But in all three cases I see the full page in fiddler.
What can I do, to get the full page? The web page I'm try to read is not under my control.
The solutions in "HTTPWebResponse Response string is truncated" do not change anything.

Text API intergration issue - Error 405 page not found

I am using Innovative Text SMS API gateway which is through me error.
Documentation is available at link http://www.innovativetxt.com/services/sms_api_gateway.htm, the error is happening on my local machine, but works fine at the production server.
The remote server returned an error: (405) Method Not Allowed.
at this line of code:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
try
{
// InnovativeTXT POST URL
string url = "http://innovativetxt.com/cp/api";
// XML-formatted data
string toSender = "4477878585244";
string fromSender = "Test";
string textMessage = "Thanks for Choosing Innovative Text Messaging Solution.";
string fields = "?to=" + toSender + "&from=" + fromSender + "&text=" + textMessage + "&api_key=xxx&api_secret=xxxxx";
url = url + fields;
// web request start
Uri uri = new Uri(url);
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
// create a request on behalf of uri
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// setting parameter for the request
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
// a stream writer for the request
StreamWriter writer = new StreamWriter(request.GetRequestStream());
// write down the date
writer.Write(data);
//close the stream writer
writer.Close();
// getting response from the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
// to write a http response from the characters
Response.Write(readStream.ReadToEnd());
// close the response
response.Close();
// close the reader
readStream.Close();
}
}
catch (Exception exp)
{
// catch for unhelded exception
Response.Write(exp.Message);
}
This issue relates to IIS Handler mappings.
You should specify the file name at the end of string URL:
string url = "http://innovativetxt.com/cp/api/somepage.aspx";
You can use default pages like, default.aspx or index.php etc...

How can I discover why a given HTTP request failed?

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

Asp.net mvc3 C#, trace 500 error response message?

I need to get the 500 error response message from HttpWebResponse.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
Thank you!
[EDIT]
open this url using browser,
https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_PRIOR_AUTH_SALE
The browser will print response message, 'Missing parameter: M_ID."
Now, I want to get that response message using asp.net
var post_string = "hello=hi";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_PRIOR_AUTH_SALE");
objRequest.Method = "POST";
objRequest.ContentLength = post_string.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
// post data is sent as a stream
StreamWriter myWriter = null;
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(post_string);
myWriter.Close();
// returned values are returned as a stream, then read into a string
try
{
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
Response.Write(post_response);
}
catch(WebException e)
{
Response.Write("Error : "+e.Message);
Response.Write("<br /> Data : " + e.Data);
Response.Write("<br /> HelpLink : " + e.HelpLink);
Response.Write("<br /> InnerException : " + e.InnerException);
Response.Write("<br /> Response : " + e.Response);
Response.Write("<br /> Source : " + e.Source);
Response.Write("<br /> Status : " + e.Status);
Response.Write("<br /> TargetSite : " + e.TargetSite);
}
Result :
Error : The remote server returned an error: (500) Internal Server Error.
Data : System.Collections.ListDictionaryInternal
HelpLink :
InnerException :
Response : System.Net.HttpWebResponse
Source : System
Status : ProtocolError
TargetSite : System.Net.WebResponse GetResponse()
How to get this message ?
Missing parameter: M_ID.
I think you need to check the StatusCode & StatusDescription properties of the web response if an exception is thrown during the web request.
For example:
try
{
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
}
catch(WebException wex)
{
// This is the line that gets you the response object
HttpWebResponse response = (HttpWebResponse)wex.Response;
if(response != null)
{
// You can now read the response StatusCode and StatusDescription
HttpStatusCode responseCode = response.StatusCode;
String statusDescription = response.StatusDescription;
// Add your status checking logic here
}
}
HTTP Errors are handled at the IIS level unless you have custom errors turned on. Check out this post on how to change your web config to add your own custom error pages: Returning 404 Error ASP.NET MVC 3
This question:
How to send a Status Code 500 in ASP.Net and still write to the response?
...also features specifically how a 500 might be thrown and again how to do customer errors. It also includes a bit on Context.Response.TrySkipIisCustomErrors which is the accepted answer.
That's work in my situation. Hope it wold help you.
try
{
response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
responseMessage = streamReader.ReadToEnd();
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
response.Close();
}
}
catch(WebException ex)
{
using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream()))
{
responseMessage = streamReader.ReadToEnd();
File.WriteAllText(#"C:\Users\Paul\Documents\text.txt", responseMessage);
}
}

Get proper response from http call, not exception

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

Categories