C# XMLDocument.Load(url) 通过代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/124932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:41:26  来源:igfitidea点击:

XMLDocument.Load(url) through a proxy

提问by lomaxx

I have a bit of code that basically reads an XML document using the XMLDocument.Load(uri) method which works fine, but doesn't work so well if the call is made through a proxy.

我有一些代码基本上使用 XMLDocument.Load(uri) 方法读取 XML 文档,该方法工作正常,但如果调用是通过代理进行的,则效果不佳。

I was wondering if anyone knew of a way to make this call (or achieve the same effect) through a proxy?

我想知道是否有人知道通过代理进行此调用(或达到相同效果)的方法?

采纳答案by Brandon Payton

Do you have to provide credentials to the proxy?

您是否必须向代理提供凭据?

If so, this should help: "Supplying Authentication Credentials to XmlResolver when Reading from a File" http://msdn.microsoft.com/en-us/library/aa720674.aspx

如果是这样,这应该会有所帮助:“从文件读取时向 XmlResolver 提供身份验证凭据” http://msdn.microsoft.com/en-us/library/aa720674.aspx

Basically, you...

基本上,你...

  1. Create an XmlTextReader using the URL
  2. Set the Credentials property of the reader's XmlResolver
  3. Create an XmlDocument instance and pass the reader to the Load method.
  1. 使用 URL 创建 XmlTextReader
  2. 设置 reader 的 XmlResolver 的 Credentials 属性
  3. 创建一个 XmlDocument 实例并将读取器传递给 Load 方法。

回答by aku

You can't configure XMLDocument to use proxy. You can use WebRequest or WebClient class to load data via proxy and pass obtained response stream to XMLDocument

您不能将 XMLDocument 配置为使用代理。您可以使用 WebRequest 或 WebClient 类通过代理加载数据并将获得的响应流传递给 XMLDocument

Also you can try to use XmlTextReader class. It allows you set network credentials. For details see:

您也可以尝试使用 XmlTextReader 类。它允许您设置网络凭据。详情请见:

Supplying Authentication Credentials to XmlResolver when Reading from a File

从文件读取时向 XmlResolver 提供身份验证凭据

回答by Alexander Kojevnikov

You need to use WebProxyand WebRequest to download the xml, then parse it.

您需要使用WebProxy和 WebRequest 下载 xml,然后对其进行解析。

回答by lomaxx

This is the code that I ended up using:

这是我最终使用的代码:

WebProxy wp = new WebProxy(Settings.Default.ProxyAddress);
wp.Credentials = new NetworkCredential(Settings.Default.ProxyUsername, Settings.Default.ProxyPassword);
WebClient wc = new WebClient();
wc.Proxy = wp;

MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTextReader rdr = new XmlTextReader(ms);
return XDocument.Load(rdr); 

回答by lomaxx

Use lomaxx's answer but change

使用 lomaxx 的答案但改变

MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTextReader rdr = new XmlTextReader(url);

to

MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTextReader rdr = new XmlTextReader(ms);