Home > Backend Development > C++ > How to Log HTTP Request and Response JSON Messages using HttpClient?

How to Log HTTP Request and Response JSON Messages using HttpClient?

Patricia Arquette
Release: 2024-12-31 14:22:10
Original
358 people have browsed it

How to Log HTTP Request and Response JSON Messages using HttpClient?

Logging HTTP Request and Response Messages using HttpClient

In situations where you need to capture the request and response messages during HTTP communication using HttpClient, logging becomes essential. Consider the following code snippet:

var response = await client.PostAsJsonAsync(url, entity);

if (response.IsSuccessStatusCode)
{
    return await response.Content.ReadAsAsync<T>();
}
Copy after login

Now, let's explore how to obtain the JSON payload sent within the 'entity' object without manually serializing it.

Solution: Custom Logging Handler

To intercept and log request and response messages, you can create a custom logging handler that wraps around the HttpClientHandler. This handler will intercept requests before HttpClientHandler processes them. An example implementation could be:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }
}
Copy after login

In this handler:

  • Console.WriteLine(request.Content.ReadAsStringAsync()) reads the request content, which causes the formatter to serialize the entity object into JSON.
  • Console.WriteLine(response.Content.ReadAsStringAsync()) does the same for the response content.

Chaining the Logging Handler with HttpClient

To use the logging handler, you need to chain it to your HttpClient:

HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
Copy after login

Example Output

The output of the above code would look like this:

Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
    Content-Type: application/json; charset=utf-8
}
"Hello, World!"

Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
    Date: Fri, 20 Sep 2013 20:21:26 GMT
    Server: Microsoft-HTTPAPI/2.0
    Content-Length: 15
    Content-Type: application/json; charset=utf-8
}
"Hello, World!"
Copy after login

By utilizing this approach, you can effectively log the request and response JSON messages during HTTP calls made with HttpClient, providing valuable insights for debugging and troubleshooting purposes.

The above is the detailed content of How to Log HTTP Request and Response JSON Messages using HttpClient?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template