C# 从HTTPClient响应解压缩GZip流
我正在尝试连接到一个api,该api从WCF服务(WCF服务到WCF服务)返回GZip编码的JSON。我正在使用HTTPClient连接到API,并且能够以字符串形式返回JSON对象。但是,我需要能够将返回的数据存储在数据库中,因此我认为最好的方法是将JSON对象返回并存储在数组或字节中,或者沿着这些线存储 具体来说,我遇到的问题是GZip编码的解压缩,我已经尝试了很多不同的例子,但仍然无法得到它 下面的代码是如何建立连接并获得响应的,这是从API返回字符串的代码C# 从HTTPClient响应解压缩GZip流,c#,json,wcf,gzip,C#,Json,Wcf,Gzip,我正在尝试连接到一个api,该api从WCF服务(WCF服务到WCF服务)返回GZip编码的JSON。我正在使用HTTPClient连接到API,并且能够以字符串形式返回JSON对象。但是,我需要能够将返回的数据存储在数据库中,因此我认为最好的方法是将JSON对象返回并存储在数组或字节中,或者沿着这些线存储 具体来说,我遇到的问题是GZip编码的解压缩,我已经尝试了很多不同的例子,但仍然无法得到它 下面的代码是如何建立连接并获得响应的,这是从API返回字符串的代码 public string g
public string getData(string foo)
{
string url = "";
HttpClient client = new HttpClient();
HttpResponseMessage response;
string responseJsonContent;
try
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = client.GetAsync(url + foo).Result;
responseJsonContent = response.Content.ReadAsStringAsync().Result;
return responseJsonContent;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return "";
}
}
我一直在遵循一些不同的例子,比如这些,还有一些关于stackoverflow的例子,但是我没有能够让这些对我有用
实现这一目标的最佳方式是什么?我是否走上了正确的轨道
谢谢大家。好吧,我终于解决了我的问题。如果有更好的方法,请告诉我:-) 创建上述类的最简单方法是使用相应的格式,并提供正确的数据类型 以下是另一个答案 同样,它没有考虑嵌套JSON
internal static class ExtentsionHelpers
{
public static DataSet ToDataSet<T>(this List<RootObject> list)
{
try
{
Type elementType = typeof(RootObject);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
try
{
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
try
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
try
{
//go through each property on T and add each value to the table
foreach (RootObject item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
insert.insertCategories(t);
return ds.
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return null;
}
}
};
因此,上面的工作是将JSON从webAPI插入数据库。这是我要做的事情。但我决不期望它是完美的。如果您有任何改进,请相应地更新。好的,我最终解决了我的问题。如果有更好的方法,请告诉我:-) 创建上述类的最简单方法是使用相应的格式,并提供正确的数据类型 以下是另一个答案 同样,它没有考虑嵌套JSON
internal static class ExtentsionHelpers
{
public static DataSet ToDataSet<T>(this List<RootObject> list)
{
try
{
Type elementType = typeof(RootObject);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
try
{
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
try
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
try
{
//go through each property on T and add each value to the table
foreach (RootObject item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
insert.insertCategories(t);
return ds.
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return null;
}
}
};
因此,上面的工作是将JSON从webAPI插入数据库。这是我要做的事情。但我决不期望它是完美的。如果您有任何改进,请相应地进行更新。只需像下面这样实例化HttpClient:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler)) //see update below
{
// your code
}
2020年6月19日更新:
不建议在“使用”块中使用httpclient,因为它可能会导致端口耗尽
private static HttpClient client = null;
ContructorMethod()
{
if(client == null)
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
client = new HttpClient(handler);
}
// your code
}
如果使用.NETCype 2.1 +,请考虑在启动代码中使用和注入这样的代码。
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(60));
services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(request => timeout);
var timeout=Policy.TimeoutAsync(
时间跨度从秒(60));
services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler
{
AutomaticDecompression=DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(请求=>超时);
只需像这样实例化HttpClient:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler)) //see update below
{
// your code
}
2020年6月19日更新:
不建议在“使用”块中使用httpclient,因为它可能会导致端口耗尽
private static HttpClient client = null;
ContructorMethod()
{
if(client == null)
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
client = new HttpClient(handler);
}
// your code
}
如果使用.NETCype 2.1 +,请考虑在启动代码中使用和注入这样的代码。
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(60));
services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(request => timeout);
var timeout=Policy.TimeoutAsync(
时间跨度从秒(60));
services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler
{
AutomaticDecompression=DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(请求=>超时);
我使用下面链接中的代码来解压GZip流。然后使用解压后的字节数组来获取所需的JSON对象。希望它能帮助一些人
var readTask = result.Content.ReadAsByteArrayAsync().Result;
var decompressedData = Decompress(readTask);
string jsonString = System.Text.Encoding.UTF8.GetString(decompressedData, 0, decompressedData.Length);
ResponseObjectClass responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseObjectClass>(jsonString);
我使用下面链接中的代码来解压GZip流,然后使用解压后的字节数组来获取所需的JSON对象。希望它能帮助一些人
var readTask = result.Content.ReadAsByteArrayAsync().Result;
var decompressedData = Decompress(readTask);
string jsonString = System.Text.Encoding.UTF8.GetString(decompressedData, 0, decompressedData.Length);
ResponseObjectClass responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseObjectClass>(jsonString);
您应该在
中使用()
语句创建HttpClient
和HttpResponse
,以确保正确、及时地处理和关闭底层流。您应该在中使用()
语句创建HttpClient
和HttpResponse
,以确保正确,及时处理和关闭底层流。@FoxDeploy使用此解决方案时,无需更改代码即可获取内容。请参阅此处以供参考:尽管这是一篇旧文章,但这个答案刚刚解决了我在.netcore中的问题,从1.1移动到2.0。客户端似乎自动进行解压缩,因此我不得不在2.0中添加此代码以使其正常工作。。。谢谢只是为了借助@SebastianCastaldi,但是.net core 1.1已经正确设置了AutomaticDecompression,但是在.net core 2.0中它被设置为NONE。我花了太长时间才弄明白……注意:HttpClient
不应该在中使用np!当集群中主机上的每个虚拟机都停止工作并抱怨端口时,我学到了艰难的方法。花了几周时间才发现这是一个应用程序没有正确使用HttpClient。@FoxDeploy使用此解决方案时,无需更改代码即可获取内容。请参阅此处以供参考:尽管这是一篇旧文章,但这个答案刚刚解决了我在.netcore中的问题,从1.1移动到2.0。客户端似乎自动进行解压缩,因此我不得不在2.0中添加此代码以使其正常工作。。。谢谢只是为了借助@SebastianCastaldi,但是.net core 1.1已经正确设置了AutomaticDecompression,但是在.net core 2.0中它被设置为NONE。我花了太长时间才弄明白……注意:HttpClient
不应该在中使用np!当集群中主机上的每个虚拟机都停止工作并抱怨端口时,我学到了艰难的方法。花了几周时间才发现这是一个没有正确使用HttpClient的应用。“最好的方法是返回JSON对象并将其存储在数组或字节中”注意,字符串是字节数组。“最好的方法是返回JSON对象并将其存储在数组或字节中”注意,字符串是字节数组。