使用WebRequest获取XML文档时,服务器返回500错误

时间:2013-09-05 03:21:11

标签: c# httpwebrequest xmldocument

这是我从传入的网址获取xml文档的代码。

var request = WebRequest.Create(url);
                    request.Method = "GET";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = 0;

                    var response = request.GetResponse(); // Error is thrown here

当我将网址复制并粘贴到我的浏览器中时,它可以正常工作。

这是返回的完整xml

<Model>
   <Item>
     <Id>7908</Id>
   </Item>
</Model>

xml格式是否错误?我已经尝试将内容类型更改为application / xml但我仍然收到此错误。

EDIT ============================================== =========

我正在尝试使用此代码使用webclient:

using (var wc = new System.Net.WebClient())
                {
                    wc.Headers["Method"] = "GET";
                    wc.Headers["ContentType"] = "text/xml;charset=\"utf-8\"";
                    wc.Headers["Accept"] = "text/xml, */*";
                    wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; .NET CLR 3.5.30729;)";
                    wc.Headers[HttpRequestHeader.AcceptLanguage] = "en-us";
                    wc.Headers["KeepAlive"] = "true";
                    wc.Headers["AutomaticDecompression"] = (DecompressionMethods.Deflate | DecompressionMethods.GZip).ToString();

                    var response = wc.DownloadString(url);
                }

响应字符串为空!!!任何想法为什么这不返回任何结果,但将URL粘贴到浏览器返回xml?

3 个答案:

答案 0 :(得分:2)

我终于开始工作了。我不得不使用这段代码:

using (var wc = new System.Net.WebClient())
                {
                    wc.Headers["Method"] = "GET";
                    wc.Headers["Accept"] = "application/xml";

                    var response = wc.DownloadString(url);
                }

密钥是使用“application / xml”的accept标头,否则响应将返回空。

答案 1 :(得分:0)

为什么不使用WebClient。

public class MyWebClient : WebClient
{

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request.GetType() == typeof(HttpWebRequest)){
            ((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36";
        }
        return request;
    }
}

using(var wc = new MyWebClient()){
    var response = wc.DownloadString(url);
    //do stuff with response
}

答案 2 :(得分:0)

这应该可以做到这一点:

try 
{
  using(var response = (HttpWebResponse)request.GetResponse())
  {
    // Do things
  }
}
catch(WebException e)
{
   // Handled!...
}

如果失败,请尝试Joel Lee的建议。