HttpClient
ã§POSTãPUTã®ãããªéä¿¡ãè¡ãå ´åã«ãBodyã§éä¿¡ããã³ã³ãã³ããGZipå§ç¸®ãããã¨æã£ãã®ã§ãããæå¤ã¨ããã«ä½¿ãããµã³ãã«ã³ã¼ããè¦å½ããã¾ããã§ããã
ã¨ããããåãã³ã¼ãã¯æ¸ããã®ã§ãã¡ã¢ãã¦ããããã¨æãã¾ããBodyã§éä¿¡ããã³ã³ãã³ãã¯ãæ½è±¡ã¯ã©ã¹ã§ããHttpContent
ã§æ±ãã®ã§ãããåç´ãªæååã®å ´åã¯StringContent
ãã¹ããªã¼ã ã®å ´åã¯StreamContent
ãªã©ç¨æããã¦ããå
·è±¡ã¯ã©ã¹ãå©ç¨ã§ãããã¨ãããã¾ãã
ããGZipå§ç¸®ã§ããã¯ã©ã¹ã¯ãªããããªã®ã§ãèªåã§HttpContentãç¶æ¿ããå¿
è¦ãããããã§ãã主ã«å¿
è¦ãªã®ã¯ãSerializeToStreamAsync
ã§å¼æ°ã®Streamã«GZipå§ç¸®ããã³ã³ãã³ããæ¸ãè¾¼ãå¦çã§ããã¾ããå®è£
ããéã«ã¯éä¿¡ããã³ã³ãã³ããã³ã³ã¹ãã©ã¯ã¿ãªã©ã§åãåãå¿
è¦ãããã¾ããä»åéä¿¡ããã³ã³ãã³ãã¯æååçµåã§çæãã¦ããã®ã§ãZStringã®Utf8ValueStringBuilder
ã§æ¸¡ãã¦ã¹ããªã¼ã ã«æ¸ãè¾¼ããã¨ã«ãã¾ããã
ã¨ããããã§ãã®ããã«å®è£ ãã¾ããã
using Cysharp.Text; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Threading.Tasks; public class GZipZStringContent : HttpContent { private readonly Utf8ValueStringBuilder sb; public GZipZStringContent(Utf8ValueStringBuilder sb) { Headers.TryAddWithoutValidation("Content-Type", "application/gzip"); Headers.ContentEncoding.Add("gzip"); this.sb = sb; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { var gzipStream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true); return sb.WriteToAsync(gzipStream).ContinueWith(_ => { gzipStream?.Dispose(); }); } protected override bool TryComputeLength(out long length) { length = -1L; return false; } }
SerializeToStreamAsync
ã¡ã½ããã§ã¯ãUtf8ValueStringBuilder ã®WriteToAsync
ã¡ã½ããã使ã£ã¦çæããGZipSteam
ã«ã³ã³ãã³ããæ¸ãè¾¼ãã§ãã¾ããã¾ããå®äºãããã¨ã«ãGZipStreamã®Dispose
ãå¼ã³åºãããããã«ãã¦ãã¾ããZStringã§ã¯ãªãå¥ã®ãã®ã§åã渡ãããå ´åã¯ãã³ã³ã¹ãã©ã¯ã¿ã§åãåã£ããã®ãGZipStreamã«æ¸ãè¾¼ãããã«å¦çãå¤ããã°åé¡ãªãã¯ãã§ãã
ã¾ããã³ã³ã¹ãã©ã¯ã¿ã§ã¯Content-Type
ã¨Content-Encoding
ãããã¼ãè¨å®ãã¦ãã¾ããTryComputeLength
ã¯ã³ã³ãã³ãã®ãµã¤ãºãä½ã³ã¹ãã§ãããå ´åã®ã¿æ£ããæ°å¤ãè¿ãã®ã§ãä»åã¯è¨ç®ããªãããã«å®è£
ãã¦ãã¾ãã
å©ç¨ããã¨ãã¯ãã®ããã«ãªãã¾ãã
// ãµã³ãã«ãªã®ã§é½åº¦çæãã¦ããããHttpClientã®ã¤ã³ã¹ã¿ã³ã¹çæã¯é©åã«ã var client = new HttpClient(); var endpoint = "https://example.com/log/v1"; using var sb = ZString.CreateUtf8StringBuilder(); sb.Append("[{\"logs\": ["); // ããã«sbã«è¿½è¨ sb.Append("]}]"); var res = await client.PostAsync(Endpoint, new GZipZStringContent(sb)); res.EnsureSuccessStatusCode();
ãªããå¦çå ¨ä½ã¨ãã¦ã¯æè¿å ¬éããã©ã¤ãã©ãªã®ãã®ã¯ã©ã¹ã«è¨è¿°ãã¦ãã¾ãã