Postman returns some response JSON with HTTP status code 406 but my code which is written in C# returns the same HTTP status code error message but from Catch Block.
My Requirement is
The API I am consuming always returns some response JSON either the HTTP status code 200 or 400 or any other. When I test these API from post man it show response JSON but my code returns error when I execute the following line.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Here is my complete method.
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;
}
*Note: - My code block works fine when API returns the HTTP status code 200 or 201