如何在状态代码无效时获取http响应正文

本文关键字:获取 http 响应 正文 无效 状态 代码 | 更新日期: 2023-09-27 18:00:05

我正在尝试从私人服务获取html页面内容。页面返回无效的状态代码0。但在浏览器中浏览时,页面确实会呈现。

当我尝试使用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

如何在状态代码无效时获取http响应正文

捕获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读取响应。