Sha*_*air 15 c# webclient bad-request
我基本上都在寻找同样的问题: 当服务器返回错误时,使用WebClient访问响应体的方法是什么?
但到目前为止还没有提供任何答案.
服务器返回"400错误请求"状态,但有详细的错误说明作为响应正文.
有关使用.NET WebClient访问该数据的任何想法?它只是在服务器返回错误状态代码时抛出异常.
dmp*_*lla 13
您无法从webclient获取它,但是在WebException上,您可以访问将其转换为HttpWebResponse对象的响应对象,并且您将能够访问整个响应对象.
有关更多信息,请参阅WebException类定义.
以下是来自MSDN的示例(不是处理异常的最佳方法,但它应该给你一些想法)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样检索响应内容:
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 ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
经过测试:在.Net 4.5.2上
| 归档时间: |
|
| 查看次数: |
17321 次 |
| 最近记录: |