读取实际响应而不是此代码的定义

时间:2017-05-12 09:25:45

标签: json c#-4.0 webrequest

我正在调用一个API,在发生任何错误之后,它们会向我们提供如下错误

HTTP response status : 406
{
  "status": 1,
  "errors": [
   { 
      "errorKey": "10011", 
      "errorMessage": "Outdated status received", 
      "errorField": "status"
    }
   ]
}

但是当我试图读取我得到的值The remote server returned an error: (406) Not Acceptable时。下面是我试图从响应中读取值的代码。

            string responseStr = "";
            HttpStatusCode statusCode;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(stringOrder);
            request.Headers.Add("clientId", clientId.Trim());
            request.Headers.Add("SecurityToken", BigApiKey.Trim());
            request.ContentType = "application/json";
            request.ContentLength = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            statusCode = response.StatusCode;


            try
            {
                Stream sw = response.GetResponseStream();
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    sw = new GZipStream(sw, CompressionMode.Decompress);
                }
                StreamReader reader = new StreamReader(sw, Encoding.Default);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
            catch (Exception ex)
            {
            errLog.LogsWrite(new Exception("  Error   " ));
                errLog.LogsWrite(ex);
            }
            return responseStr;

但是当服务器返回低于响应时,它才能正常工作

 {
  "status": 1,
  "errors": [
    {
      "errorKey": "1000",
      "errorMessage": "Invalid delivery status received!",
      "errorField": ""
    }
  ]
}

你可以告诉我在我的代码中我犯了什么错误。

0 个答案:

没有答案