C# 当状态代码无效时,如何获取http响应正文?
我正在尝试从私人服务获取html页面内容。 该页返回无效的状态代码0。但在浏览器中浏览时,页面确实会呈现 当我尝试使用C# 当状态代码无效时,如何获取http响应正文?,c#,http,httpresponse,http-status-codes,C#,Http,Httpresponse,Http Status Codes,我正在尝试从私人服务获取html页面内容。 该页返回无效的状态代码0。但在浏览器中浏览时,页面确实会呈现 当我尝试使用WebResponse.GetResponseStream()时,它只返回空流。 当我尝试使用HttpClient.GetStringAsync(url).Result时,它抛出AggregateException,如下所示: System.AggregateException was unhandled HResult=-2146233088 Message=One o
WebResponse.GetResponseStream(
)时,它只返回空流。
当我尝试使用HttpClient.GetStringAsync(url)
.Result时,它抛出AggregateException
,如下所示:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at DiagnosticInfoCrawler.Program.Main(String[] args) in c:\TFS\MSNMetro\Tools\Verticals\Sports\DiagnosticInfoCrawler\Program.cs:line 47
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Response status code does not indicate success: 0 ().
InnerException:
使用两种类型的代码,如下所示:
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
任何人都可以建议我如何获得回复机构?(假设我无法控制修复服务以返回正确的状态代码。)
谢谢,,
DD捕获
WebException
以获取响应。这是微软糟糕的设计决策,因为非200代码可能是正常情况的一部分
try
{
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
}
catch (WebException exception)
{
var response = (HttpWebResponse)exception.GetResponse();
//the response is here..
}
没有直接解决此问题,而是采用了使用TcpClient读取响应的方法。谢谢jgauffin,但此处引发的异常实际上是System.AggregateException,因此Catch(WebException ex)甚至不会捕获。AggregateException包含多个异常。其中一个是WebExceptionNo,innerException是一个HttpRequestException,不能将其转换回WebException