[英]How to get response JSON of an API which returns Http Status Code 406 or 400
Postman 返回一些带有 HTTP 状态代码 406 的响应 JSON,但我用 C# 编写的代码返回相同的 HTTP 状态代码错误消息,但来自 Catch Block。
我的要求是
我使用的 API 总是返回一些响应 JSON,HTTP 状态代码 200 或 400 或任何其他。 当我从邮递员那里测试这些 API 时,它显示响应 JSON,但当我执行以下行时,我的代码返回错误。
HttpWebResponse 响应 = (HttpWebResponse)request.GetResponse();
这是我的完整方法。
private Dictionary<string, string> HTTPCall(CRMRequestData requestData, out bool isError, out string errorMessage)
{
isError = true;
errorMessage = "HTTPCall - initial error!";
try
{
ServicePointManager.SecurityProtocol = TLS12;
Dictionary<string, string> responseBag = new Dictionary<string, string>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestData.Uri);
request.Method = requestData.HttpMethodName;
request.ContentType = requestData.ContentType;
request.ContentLength = string.Format("{0}", requestData.Body).Length;
request.Headers.Add("x-api-key", requestData.APIKey);
if (requestData.Authorization != null)
{
request.Headers.Add("Authorization", string.Format("JWT {0}",requestData.Authorization));
}
if (requestData.HttpMethodName.ToUpper().Equals("POST"))
{
string body = requestData.Body;
Byte[] bytes = Encoding.UTF8.GetBytes(body);
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//#Error at this line
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (responseData != null && responseData != "")
{
responseBag = ReadResponseJSON(responseData, requestData.CRMMethod, out isError, out errorMessage);
}
errorMessage = (!isError) ? "HTTPCall - API executed successfully!" : errorMessage;
return responseBag;
}
catch (Exception ex)
{
isError = true;
errorMessage = string.Format("{0}", ex.Message);
}
return null;
}
*注意: -当 API 返回 HTTP 状态代码 200 或 201 时,我的代码块工作正常
试试这个: 什么是 HTTP 中的“406-Not Acceptable Response”?
简而言之:为 Service 返回的响应(内容类型)添加 Accept 标头
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.