1

这是我从传入的 url 获取 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

当我将 url 复制并粘贴到浏览器中时,它工作得很好。

这是返回的完整 xml

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

xml 格式是否不正确?我尝试将内容类型更改为 application/xml,但仍然出现此错误。

编辑================================================== ======

我正在尝试使用以下代码使用 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?

4

3 回答 3

2

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

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

                    var response = wc.DownloadString(url);
                }

关键是使用“application/xml”的接受标头,否则响应将返回空。

于 2013-09-08T22:40:16.590 回答
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
}
于 2013-09-05T03:52:37.217 回答
0

这应该有望解决问题:

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

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

于 2013-09-05T04:07:49.847 回答