[英]WebClient - get response body on error status code
我基本上都在尋找同樣的問題: 當服務器返回錯誤時,使用WebClient訪問響應體的方法是什么?
但到目前為止還沒有提供任何答案。
服務器返回“400錯誤請求”狀態,但有詳細的錯誤說明作為響應正文。
有關使用.NET WebClient訪問該數據的任何想法? 它只是在服務器返回錯誤狀態代碼時拋出異常。
您無法從webclient獲取它,但是在WebException上,您可以訪問將其轉換為HttpWebResponse對象的響應對象,並且您將能夠訪問整個響應對象。
有關更多信息,請參閱WebException類定義。
以下是MSDN的示例(為了清楚起見,添加了閱讀Web響應的內容)
using System;
using System.IO;
using System.Net;
public class Program
{
public static void Main()
{
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
{
Console.WriteLine("Content: {0}", r.ReadToEnd());
}
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
}
}
您可以像這樣檢索響應內容:
using (WebClient client = new WebClient())
{
try
{
string data = client.DownloadString(
"http://your-url.com");
// successful...
}
catch (WebException ex)
{
// failed...
using (StreamReader r = new StreamReader(
ex.Response.GetResponseStream()))
{
string responseContent = r.ReadToEnd();
// ... do whatever ...
}
}
}
經過測試:在.Net 4.5.2上
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.