How to get json response using system.net.webrequest in c?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
When working with REST APIs in C#, you need a way to send HTTP requests and parse the JSON that comes back. The System.Net.WebRequest class was the original approach for making HTTP calls in .NET. While HttpClient is now the recommended choice for new projects, understanding WebRequest is still valuable for maintaining legacy codebases and for grasping how HTTP communication works at a lower level in .NET.
Setting Up an HttpWebRequest
WebRequest.Create returns a WebRequest instance, which you cast to HttpWebRequest to access HTTP-specific properties like Method, ContentType, and Accept. Setting the Accept header to application/json tells the server you expect a JSON response.
The using blocks ensure that the response, stream, and reader are disposed of properly. Neglecting disposal can cause connection pool exhaustion under load.
Deserializing the JSON Response
Raw JSON strings are rarely useful on their own. Use System.Text.Json (built into .NET Core and .NET 5+) or Newtonsoft.Json to convert the string into a strongly typed object.
If you are on .NET Framework (not .NET Core), you can use Newtonsoft.Json instead:
Setting PropertyNameCaseInsensitive = true in System.Text.Json handles the common case where the API returns camelCase keys (name) but your C# properties use PascalCase (Name).
Handling Errors
WebRequest throws a WebException when the server returns a non-success status code. You should catch this exception, read the error response body, and handle it appropriately.
The WebException.Response property gives you access to the full error response, including the status code and body, which often contains a JSON error message from the API.
The Modern Alternative With HttpClient
For new code, HttpClient is simpler, supports async/await, and handles connection pooling more efficiently. Here is the equivalent operation:
Notice that HttpClient is instantiated once and reused. Creating a new HttpClient per request is a well-known mistake that leads to socket exhaustion. If you are on .NET Core 2.1 or later, consider using IHttpClientFactory for even better lifecycle management.
Common Pitfalls
- Not disposing the response and streams:
HttpWebResponseholds a network connection. If you skip theusingblock or forget to callClose(), connections leak and eventually the application cannot make new requests. - Creating a new
HttpClientper request: This applies to the modern alternative. Each instance holds its own connection pool, and rapid creation/disposal exhausts available sockets. DeclareHttpClientas a static or singleton. - Ignoring non-success status codes with
WebRequest:GetResponse()throwsWebExceptionfor 4xx/5xx codes. If you catch and swallow the exception without reading the error body, you lose the server's error details. - Hardcoding
http://instead ofhttps://: Modern APIs require TLS. Using plain HTTP either fails or exposes credentials in transit. Always default to HTTPS unless you have a specific reason for plain HTTP. - Assuming JSON property names match C# conventions: APIs typically use camelCase or snake_case. Without
PropertyNameCaseInsensitive = trueor[JsonPropertyName]attributes, deserialization silently produces null or default values for mismatched properties.
Summary
- Use
WebRequest.Createcast toHttpWebRequestto configure HTTP method, headers, and content type for JSON API calls. - Read the response by wrapping
GetResponseStream()in aStreamReaderinsideusingblocks to prevent connection leaks. - Deserialize JSON with
System.Text.Json.JsonSerializer.Deserialize\<T>orNewtonsoft.Json.JsonConvert.DeserializeObject\<T>. - Catch
WebExceptionand inspectex.Responseto extract HTTP status codes and error bodies from failed requests. - For new projects, prefer
HttpClientwith a singleton or factory pattern for cleaner async code and proper connection management.
Related reading
- How to get Kubernetes cluster name from K8s API
- How to get mac host IP address from a docker container?
- How to get my IP address programmatically on iOS/macOS?
- How to get Python requests to trust a self signed SSL certificate?
- How to get next or previous enum value in C
- How to get only filenames within a directory using c?
- How to get running pod status via Rest API
- How to get self pod with kubernetes client-go

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.