2016-02-05 302 views
1

我用於部首像GZIP響應請求:獲取異常Newtonsoft.Json.JsonReaderException

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; 
    } 
+0

提供更多信息。什麼是json,什麼是類型參數T –

+0

如何構建您的請求,如果您共享代碼,這將會很有幫助。 –

+0

我已更新我的問題@HariPrasad –

回答

2

你必須設置您的要求AutomaticDecompression財產。

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

更新:

可以包括以下線在CreateWebRequest方法。

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

您可以在創建請求的'CreateWebRequest'方法中添加此項.. –

+0

@DrukGohil我更新了答案以滿足您的要求。 –

+0

感謝它的工作,但是,如何確認我獲得Gzip響應? –