使用HttpClient 記錄HTTP 請求和回應訊息
當您需要使用HttpClient 擷取HTTP 通訊過程中的回應訊息記錄變得至關重要。考慮以下程式碼片段:
var response = await client.PostAsJsonAsync(url, entity); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync<T>(); }
現在,讓我們探討如何取得「實體」物件中傳送的 JSON 負載,而無需手動序列化它。
解決方案:自訂日誌記錄Handler
要攔截並記錄請求和回應訊息,您可以建立一個自訂日誌記錄處理程序來包裝HttpClientHandler。此處理程序將在 HttpClientHandler 處理請求之前攔截請求。範例實作可以是:
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; } }
在此處理程序中:
將日誌處理程序與 HttpClient 連結
要使用日誌處理程序,您需要將其連結到您的HttpClient:
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())); HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
範例輸出
上述程式碼的輸出如下所顯示:
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!"
利用此方法,您可以在使用HttpClient 進行HTTP在呼叫期間有效地記錄請求和回應 JSON 訊息,為偵錯和故障排除提供有價值的見解。
以上是如何使用 HttpClient 記錄 HTTP 請求和回應 JSON 訊息?的詳細內容。更多資訊請關注PHP中文網其他相關文章!