How to get status code from webclient?
Tried it out. ResponseHeaders do not include status code.
If I'm not mistaken, WebClient
is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest
and HttpWebResponse
, a distinct status code may not be available.
It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.
The status code unfortunately isn't present in the ResponseHeaders
dictionary.
Get status code of Spring WebClient request
This problem can be solved with the method exchangeToMono
. This results into the following snippet.
WebClient.builder().baseUrl("url").build()
.get().exchangeToMono(response -> Mono.just(response.statusCode()))
.block();
The usage of the retrieve
method can be improved in the following way, still not very clean.
WebClient.builder().baseUrl("url").build()
.get().retrieve()
.onStatus(httpStatus -> true, clientResponse -> {
//Set variable to return here
status.set(clientResponse.statusCode());
return null;
})
.toBodilessEntity().block();
WebClient - get response body on error status code
You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.
Please see the WebException class definition for more information.
Below is an example from MSDN (added reading the content of the web response for clarity)
using System;
using System.IO;
using System.Net;
public class Program
{
public static void Main()
{
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
{
Console.WriteLine("Content: {0}", r.ReadToEnd());
}
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
}
}
WebClient StatusCode
This won't tell you the status but it can be inferred by the fact that you were redirected.
if(reponse.ResponseUri != request.RequestUri) {
// if you really want to know the status
// set AllowAutoRedirect = false;
// and send another request in here.
}
Related Topics
Learning Single Responsibility Principle with C#
Connect to Active Directory via Ldap
How to Write Output from a Unit Test
Httpwebrequest & Native Gzip Compression
Modelstate.Isvalid Even When It Should Not Be
Complex Models and Partial Views - Model Binding Issue in ASP.NET MVC 3
Bind Multiple Combobox to a Single List - Issue: When I Select an Item, All Combo Boxes Change
How to Elegantly Deal with Timezones
How to 'Await' Raising an Eventhandler Event
How to Get the Development/Staging/Production Hosting Environment in Configureservices
How to Create an Expression Tree Calling Ienumerable<Tsource>.Any(...)
Linq Aggregate and Group by Periods of Time
Automatically Start a Windows Service on Install
Upgrading Old Unity Code to Unity 5
How to Define Implicit Conversions of Enums in C#
Deserializing Heterogenous JSON Array into Covariant List<> Using JSON.Net