从 System.Net.WebRequest 获得完整回复 body
Getting full response body from System.Net.WebRequest
我正在使用 System.Net.WebRequest 从一些 API 获取信息。
当我收到错误时,响应仅包含基本的 HttpStatusCode 和消息,而不是完整的错误 returned。
为了进行比较,运行 相同的 post 数据和 headers 在 POSTMAN 等工具中将 return 来自 API 的完整错误。
我想知道是否有一些 属性 或方法可以获得完整的错误响应??
这是我的代码 运行:
public HttpStatusCode GetRestResponse(
string verb,
string requestUrl,
string userName,
string password,
out string receiveContent,
string postContent = null)
{
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = verb;
if (!string.IsNullOrEmpty(userName))
{
string authInfo = string.Format("{0}:{1}", userName, password);
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
}
if (!string.IsNullOrEmpty(postContent))
{
byte[] byteArray = Encoding.UTF8.GetBytes(postContent);
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
receiveContent = reader.ReadToEnd();
reader.Close();
return ((HttpWebResponse) response).StatusCode;
}
}
}
catch (Exception ex)
{
receiveContent = string.Format("{0}\n{1}\nposted content = \n{2}", ex, ex.Message, postContent);
return HttpStatusCode.BadRequest;
}
receiveContent = null;
return 0;
}
当我生成一个向我显示错误的请求时,我收到错误消息:The remote server returned an error: (400) Bad Request.
并且没有 InnerException,并且我无法从异常中受益。
[Answer] @Rene 指出了正确的方向和正确的响应 body 可以这样获得:
var reader = new StreamReader(ex.Response.GetResponseStream());
var content = reader.ReadToEnd();
您捕获的是一般异常,因此没有太多空间提供具体信息。
你应该赶上 specialized exception that is thrown by the several webrequest classes, namely WebException
您的捕获代码可能是这样的:
catch (WebException e)
{
var response = ((HttpWebResponse)e.Response);
var someheader = response.Headers["X-API-ERROR"];
// check header
if (e.Status == WebExceptionStatus.ProtocolError)
{
// protocol errors find the statuscode in the Response
// the enum statuscode can be cast to an int.
int code = (int) ((HttpWebResponse)e.Response).StatusCode;
string content;
using(var reader = new StreamReader(ex.Response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
// do what ever you want to store and return to your callers
}
}
在主机发送的 WebException instance you also have access to the Response
中,因此您可以访问发送给您的任何内容。
我正在使用 System.Net.WebRequest 从一些 API 获取信息。 当我收到错误时,响应仅包含基本的 HttpStatusCode 和消息,而不是完整的错误 returned。 为了进行比较,运行 相同的 post 数据和 headers 在 POSTMAN 等工具中将 return 来自 API 的完整错误。
我想知道是否有一些 属性 或方法可以获得完整的错误响应??
这是我的代码 运行:
public HttpStatusCode GetRestResponse(
string verb,
string requestUrl,
string userName,
string password,
out string receiveContent,
string postContent = null)
{
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = verb;
if (!string.IsNullOrEmpty(userName))
{
string authInfo = string.Format("{0}:{1}", userName, password);
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
}
if (!string.IsNullOrEmpty(postContent))
{
byte[] byteArray = Encoding.UTF8.GetBytes(postContent);
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = byteArray.Length;
var dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
using (WebResponse response = request.GetResponse())
{
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
receiveContent = reader.ReadToEnd();
reader.Close();
return ((HttpWebResponse) response).StatusCode;
}
}
}
catch (Exception ex)
{
receiveContent = string.Format("{0}\n{1}\nposted content = \n{2}", ex, ex.Message, postContent);
return HttpStatusCode.BadRequest;
}
receiveContent = null;
return 0;
}
当我生成一个向我显示错误的请求时,我收到错误消息:The remote server returned an error: (400) Bad Request.
并且没有 InnerException,并且我无法从异常中受益。
[Answer] @Rene 指出了正确的方向和正确的响应 body 可以这样获得:
var reader = new StreamReader(ex.Response.GetResponseStream());
var content = reader.ReadToEnd();
您捕获的是一般异常,因此没有太多空间提供具体信息。
你应该赶上 specialized exception that is thrown by the several webrequest classes, namely WebException
您的捕获代码可能是这样的:
catch (WebException e)
{
var response = ((HttpWebResponse)e.Response);
var someheader = response.Headers["X-API-ERROR"];
// check header
if (e.Status == WebExceptionStatus.ProtocolError)
{
// protocol errors find the statuscode in the Response
// the enum statuscode can be cast to an int.
int code = (int) ((HttpWebResponse)e.Response).StatusCode;
string content;
using(var reader = new StreamReader(ex.Response.GetResponseStream()))
{
content = reader.ReadToEnd();
}
// do what ever you want to store and return to your callers
}
}
在主机发送的 WebException instance you also have access to the Response
中,因此您可以访问发送给您的任何内容。