How to get error information when HttpWebRequest.GetResponse() fails
Is this possible using HttpWebRequest and HttpWebResponse?
You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.
So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
// Something more serious happened
// like for example you don't have network access
// we cannot talk about a server exception here as
// the server probably was never reached
}
Handling Errors from HttpWebRequest.GetResponse
Try this:
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
'' set up request
Try
Using response = req.GetResponse()
'' success in here
End Using
Catch ex As WebException
Console.WriteLine(ex.Status)
If ex.Response IsNot Nothing Then
'' can use ex.Response.Status, .StatusDescription
If ex.Response.ContentLength <> 0 Then
Using stream = ex.Response.GetResponseStream()
Using reader = New StreamReader(stream)
Console.WriteLine(reader.ReadToEnd())
End Using
End Using
End If
End If
End Try
C# version
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(url);
// set up request
try {
using (var response = req.GetResponse()) {
// success in here
}
}
catch (WebException ex) {
Console.WriteLine(ex.Status);
if (ex.Response != null) {
// can use ex.Response.Status, .StatusDescription
if (ex.Response.ContentLength != 0) {
using (var stream = ex.Response.GetResponseStream()) {
using (var reader = new StreamReader(stream)) {
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
}
Here's your code, modified a bit:
Try
'connect with zeep'
Dim request As HttpWebRequest = CType(WebRequest.Create( _
"https://api.zeepmobile.com/messaging/2008-07-14/send_message"), HttpWebRequest)
request.Method = "POST"
request.ServicePoint.Expect100Continue = False
' set the authorization levels'
request.Headers.Add("Authorization", "Zeep " & API_KEY & ":" & b64)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = content.Length
' set up and write to stream'
Using requestStream As Stream = request.GetRequestStream()
Using requestWriter As New StreamWriter(requestStream)
requestWriter.Write(content)
End Using
End Using
Using myWebResponse As WebResponse = request.GetResponse()
Using myResponseStream As Stream = myWebResponse.GetResponseStream()
Using myStreamReader As StreamReader = New StreamReader(myResponseStream)
Return myStreamReader.ReadToEnd()
End Using
End Using
End Using
Catch ex As WebException
Console.WriteLine(ex.Status)
If ex.Response IsNot Nothing Then
'' can use ex.Response.Status, .StatusDescription
If ex.Response.ContentLength <> 0 Then
Using stream = ex.Response.GetResponseStream()
Using reader = New StreamReader(stream)
Console.WriteLine(reader.ReadToEnd())
End Using
End Using
End If
End If
End Try
Dumping headers:
Dim headers As WebHeaderCollection = request.Headers
' Displays the headers. Works with HttpWebResponse.Headers as well
Debug.WriteLine(headers.ToString())
' And so does this
For Each hdr As String In headers
Dim headerMessage As String = String.Format("{0}: {1}", hdr, headers(hdr))
Debug.WriteLine(headerMessage)
Next
How do I read a custom error message returned when HttpWebRequest.GetResponse throws a WebException?
Here's a pared-down example which reads your custom message. Your message is returned in the response stream.
try
{
var response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex) // this exception is thrown because of the 401.
{
var responseStream = ex.Response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
var message = reader.ReadToEnd();
}
}
.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned
It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:
using System;
using System.IO;
using System.Web;
using System.Net;
public class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("Won't get here");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
}
}
You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)
If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength
to make sure you get the whole error.
HttpWebRequest call to GetResponse, fails using .net 4.5 but passes using net 4.6
This is usually caused by the server using TLS v1.2. I think Net4.5 defaults to TLS v1.1, so you must add this to your code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Getting content from httpwebresponse exception
EDIT : Have you tried with a simple try-catch to see if you can get more details ?
try
{
var response = (HttpWebResponse)(request.GetResponse());
}
catch(Exception ex)
{
var response = (HttpWebResponse)ex.Response;
}
In my recherches in an answer for you, I noticed that in code there was something about encoding, that you didn't specified. Look here for exemple with such code.
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
Or here, in the doc, also.
// Creates an HttpWebRequest with the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r\nResponse stream received.");
Have you tried with such ?
Make HttpWebRequest.GetResponse() return a value when the connection fails
GetResponse throws an exception when an error occurs. For example if host cannot be resolved. All you need is to catch it and do proper action after it.
In code below I handle WebException, but some other exceptions can occur during this method. So you can general Exception class instead.
public DateTime GetInternetTime()
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
myHttpWebRequest.Timeout = 5000;
myHttpWebRequest.ReadWriteTimeout = 5000;
try
{
var response = myHttpWebRequest.GetResponse();
string todaysDates = response.Headers["date"];
dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
connectionFailed = false;
} catch(WebException)
{
connectionFailed = true;
dateTime = DateTime.Now;
}
return dateTime;
}
Related Topics
How to Get All the Possible 3 Letter Permutations
Getting Selected Value of a Combobox
Is Correct to Use Gc.Collect(); Gc.Waitforpendingfinalizers();
Update Float Array from C++ Native Plugin
Razor Syntax Error Serializing ASP.NET Model to JSON with HTML.Raw
Add the Where Clause Dynamically in Entity Framework
C#/.Net Analysis Tool to Find Race Conditions/Deadlocks
C# Serialized JSON Date to Ruby
Entity Framework Initialization Is Slow -- What How to Do to Bootstrap It Faster
Are Java and C# Regular Expressions Compatible
C# Generics Compared to C++ Templates
Dependency Injection with a Static Logger, Static Helper Class
C# Compiler Bug? Why Doesn't This Implicit User-Defined Conversion Compile
Finding Out If a Type Implements a Generic Interface
How to Hook into Hardware Keyboard Events at an Application Level