我在Header中请求gZip响应,如:
request.Headers.Add(HttpRequestHeader.AcceptEncoding,“gzip”);
在网络回复中我得到 ContentEncoding = gzip
我不知道如何用我的代码解压缩gzip响应,当我用json读取字符串时,我得到 Newtonsoft.Json.JsonReaderException
解决方案是什么?
using (WebResponse response = GetWebResponse(request))
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
这是我构建请求的方式:
var request = CreateWebRequest(new Uri(uri), type);
// create request stream from arguments
if (args != null)
{
string requestData = string.Empty;
requestData = Newtonsoft.Json.JsonConvert.SerializeObject(args, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.GetEncoding("UTF-8").GetBytes(requestData);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
protected WebRequest CreateWebRequest(Uri uri, MethodType type, bool IsUrlEncoded = false)
{
WebRequest request = WebRequest.Create(uri);
(request as HttpWebRequest).Accept = "application/json";
System.Net.ServicePointManager.Expect100Continue = false;
if (IsUrlEncoded)
request.ContentType = "application/x-www-form-urlencoded";
else
request.ContentType = "application / json";
request.Headers.Add("X-Application", AppKeyData.Appkey);
if (!string.IsNullOrEmpty(AppKeyData.SessionToken))
{
request.Headers.Add("X-Authentication", AppKeyData.SessionToken);
}
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
request.Method = type.ToString();
return request;
}
答案 0 :(得分:3)
您必须在请求中设置AutomaticDecompression
属性。
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
<强>更新强>
您可以在CreateWebRequest
方法中添加以下内容。
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;