我有一个类使用 HttpWebRequest 发布一些 XML 并接收一些 XML。它在 Windows 应用程序上运行良好,但是当我在 ASP.Net Web 端使用它时,我得到 WebException“无法连接到远程服务器”。我认为这与通过我的公司代理有关。但我不确定如何设置凭证以便它可以在网页中工作。下面是发布 XML 的代码(m_Credentials 已使用“CredentialCache.DefaultCredentials”设置:
private string PostData(string url, string postData)
{
HttpWebRequest request=null;
Uri uri = new Uri(url);
request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
// Tell it to use our credentials else we may not get through
if (m_Credentials != null)
{
request.Proxy.Credentials = m_Credentials;
}
using(Stream writeStream = request.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
string result=string.Empty;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader (responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}