При неправильном POST
-запросе, сервер возвращает код ошибки и тело с подробным пояснением, что именно пошло не так.
Как прочитать это тело?
public static HttpRequestResult Send(string method, string url, string body, NameValueCollection headers)
{
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method;
if (!string.IsNullOrEmpty(body))
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = bodyBytes.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
using (StreamWriter streamWriter = new StreamWriter(requestStream))
{
streamWriter.Write(body);
}
}
else if (method != "GET" && method != "HEAD")
{
httpWebRequest.ContentLength = 0L;
}
if (headers != null)
{
SetRequestHeaders(httpWebRequest, headers);
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
int resultErrorCode = (int)httpResponse.StatusCode;
Stream responseStream = resultErrorCode == 200 || resultErrorCode == 206 ? httpResponse.GetResponseStream() : null;
return new HttpRequestResult(resultErrorCode, httpResponse.StatusDescription,
httpResponse, responseStream, httpResponse.ContentLength);
}
catch (System.Exception ex)
{
int errorCode;
if (ex is WebException && (ex as WebException).Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse response = (ex as WebException).Response as HttpWebResponse;
errorCode = (int)response.StatusCode;
return new HttpRequestResult(errorCode, response.StatusDescription, response, null, -1L);
}
errorCode = ex.HResult;
string errorMessage = ex.Message;
return new HttpRequestResult(errorCode, errorMessage, null, null, -1L);
}
}
На строчке
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
улетает в экскепшен.