我最初使用 WebRequest 和 WebResponse 来发送 Http Post 消息。我总是得到“确定”的回应。我发布的消息是用 xml 中的证书签名的 XML。
组成是这样的: 发送到 https 网站的 C# 服务。 我不能说的另一个地方的 HTTPS 网站。 本地 HTTPS 本地网站,它只是接收我在本地发布的消息并将结果写入文件。只是为了模拟其他网站获得的内容。
本地网站使用自签名证书签名,将于 2048 年到期。
这段代码在本周之前运行良好。我总是张贴并得到确定。在这两个网站上。但本周测试和实际项目实现都进行了 Kaput。在两个网站上。
在本地网站上显示无法连接到 SSL。
这个问题是由自签名证书引起的,出于某种我无法理解的原因,它给了 hell 。感谢这里的问题,我刚刚验证了证书始终是真实的,现在它不再被窃听了。
要解决这个问题,只需写下:
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
在您的应用程序的开头。所以它只运行一次。
剩下的问题是“远程服务器返回错误:(503) 服务器不可用。”。我在浏览器中输入 URL,它对我来说工作正常。在代码中,这个网站没有收到任何东西,当它进入网络响应时,它给了我上述错误
我做了一个只发送“Testing 1 2 3”的测试应用程序,但我一直收到错误。我也发到一个harvard https网站也没有报错。
private void btnSend_Click(object sender, EventArgs e)
{
try
{
WebRequest req = WebRequest.Create(cboUrl.Text);
req.PreAuthenticate = true;
req.UseDefaultCredentials = true;
req.Method = "POST";
req.ContentType = "text/xml";
String msg = txtMsg.Text;
using (Stream s = req.GetRequestStream())
{
try
{
s.Write(
System.Text.ASCIIEncoding.ASCII.GetBytes(msg), 0, msg.Length);
}
finally
{
s.Close();
}
}
WebResponse resp = req.GetResponse();
StreamReader str = new StreamReader(resp.GetResponseStream());
txtRes.Text = str.ReadToEnd();
}
catch (WebException ex)
{
txtRes.Text = ex.Message;
}
catch (Exception ex)
{
txtRes.Text = ex.Message;
}
}
这是我根据在互联网上找到的内容构建的另一个示例:
private void button1_Click(object sender, EventArgs e)
{
try
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(cboUrl.Text);
myReq.Headers.Clear();
myReq.Method = "POST";
myReq.KeepAlive = false;
myReq.ProtocolVersion = HttpVersion.Version11;
myReq.ContentType = "text/xml";
myReq.Proxy = null;
myReq.Credentials = null;
myReq.ContentLength = txtMsg.Text.Length;
using (StreamWriter sendingData = new StreamWriter(myReq.GetRequestStream()))
{
sendingData.Write(txtMsg.Text);
sendingData.Flush();
sendingData.Close();
}
HttpWebResponse myResponse = (HttpWebResponse) myReq.GetResponse();
StreamReader responseStream = new StreamReader(myResponse.GetResponseStream());
txtRes.Text = responseStream.ReadToEnd();
responseStream.Close();
myResponse.Close();
}
catch(WebException ex )
{
txtRes.Text = ex.Message;
}
catch (Exception ex)
{
txtRes.Text = ex.Message;
}
}
更新
错误是我用 httpwebrequest 调用的那个需要一些我没有提供的 httpheaders。在唯一发生的事情之前,我得到了一个“OK”的回应。他们修复了他们的代码,我修复了我的代码,现在它可以正常工作了。
如果它发生在其他人身上,请像下面所说的那样检查代理设置,并检查另一方是否给出异常或根本不返回任何内容。
最佳答案
如果您在浏览器中导航到 URL 时没有收到 503 错误,但是在使用 HttpWebRequest 请求资源时确实收到了它,我首先要做的是建议您在发出请求时为 UserAgent 指定一个值。
您可能还想使用 Fiddler2或其他工具,以更好地了解请求生命周期内发生的情况。如果不了解您要向其发布消息的服务的详细信息,就很难提供指导。
关于ssl - HttpWebRequest Server Unavailable 503问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/303611/