gpt4 book ai didi

c# - 获取异常 Newtonsoft.Json.JsonReaderException

转载 作者:行者123 更新时间:2023-11-30 21:51:47 24 4
gpt4 key购买 nike

我在 header 中请求 gZip 响应,例如:

request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");

在 webresponse 中我得到 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;
}

最佳答案

你必须设置 AutomaticDecompression根据您的要求提供属性(property)。

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

更新:

您可以在 CreateWebRequest 方法中包含以下行。

(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

关于c# - 获取异常 Newtonsoft.Json.JsonReaderException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com