c# - 如何在 post/put 请求中读取压缩数据(API 端)
问题描述
我正在尝试通过使用 gZip 压缩数据来减小请求大小。我有作为 json 发送的工作 post/put 请求,我想向他们发送 gZip。
对于服务器到客户端的方式,我得到了它:
services.AddResponseCompression(o =>
{
o.Providers.Add<GzipCompressionProvider>();
});
app.UseResponseCompression();
对于客户端到服务器的方式,我无法让它工作。我添加了这种压缩方法:
private static byte[] Zip(string str)
{
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
//msi.CopyTo(gs);
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
private static void CopyTo(Stream src, Stream dest)
{
var bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) dest.Write(bytes, 0, cnt);
}
我这样发送请求:
internal static async Task<object> PostAsync(string request, object value, string token = null)
{
//Create the http client to send the request
using (var client = new HttpClient())
{
//Add the token from the user
if (!string.IsNullOrEmpty(token))
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
var serializedValues = SerializeSplitter(value);
var output = new List<bool>();
//Wait for the server response
foreach (var serializedValue in serializedValues)
{
var response = await client
.PostAsync(Host + request, new StringContent(Encoding.UTF8.GetString(Zip(serializedValue)), Encoding.UTF8, "application/json"))
.ConfigureAwait(false);
output.Add(response.IsSuccessStatusCode);
}
//TODO Add error manager
return output.All(i => i);
}
}
当我发送请求时,我得到一个 BadRequest 400 :
{
"errors": {
"": [
"Unexpected character encountered while parsing value: \u001f. Path '', line 0, position 0."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "0HLN405BDHU0T:00000001"
}
解决方案
推荐阅读
- go - Cloud SQL 连接与 Kubernetes/Proxy Side Car
- r - 如何将毫秒数据转换为R中的时间序列
- c# - 将命令行参数传递给控制台应用程序不起作用
- javascript - 用多个其他范围计算矩范围的覆盖率
- python - 将列表列表合并到数据框熊猫中
- c# - 使用 HttpClient 从 SOAP 发布请求中检索响应字段
- gcc - 如何禁用 Eigen 中内置函数的使用(它定义了该架构的 pikc 指令)
- reporting-services - 从客户端计算机加载 SSRS 2008 R2 报告时出现间歇性错误
- cors - 通过 Dropbox 服务 CSS 突然停止工作
- maven - gitlab-ci 和 maven 元数据