我试图从私人服务获取HTML页面内容。 该页面返回状态代码0,该代码无效。但是在浏览浏览器时页面会进行渲染。
当我尝试使用WebResponse.GetResponseStream(
)时,它只返回空流。
当我尝试使用HttpClient.GetStringAsync(url)
。结果时,它会抛出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
答案 0 :(得分:1)
抓住WebException
以获得回复。这是Microsoft的一个糟糕的设计决定,因为非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..
}
答案 1 :(得分:0)
没有直接解决这个问题,而是转向使用TcpClient来读取响应的方法。