gpt4 book ai didi

c# - 通过 SSL 使用 HttpWebRequest 发送请求时出现错误 502(错误的网关)

转载 作者:IT王子 更新时间:2023-10-29 04:23:06 25 4
gpt4 key购买 nike

我在经典 ASP 中有以下代码片段,用于发送命令并通过 SSL 检索响应:

Dim xmlHTTP
Set xmlHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
xmlHTTP.open "POST", "https://www.example.com", False
xmlHTTP.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
xmlHTTP.setRequestHeader "Content-Length", Len(postData)
xmlHTTP.Send postData
If xmlHTTP.status = 200 And Len(message) > 0 And Not Err Then
Print xmlHTTP.responseText
End If

然后我用了this code作为在 c# 中重新实现请求的引用:

private static string SendRequest(string url, string postdata)
{
WebRequest rqst = HttpWebRequest.Create(url);
// We have a proxy on the domain, so authentication is required.
WebProxy proxy = new WebProxy("myproxy.mydomain.com", 8080);
proxy.Credentials = new NetworkCredential("username", "password", "mydomain");
rqst.Proxy = proxy;
rqst.Method = "POST";
if (!String.IsNullOrEmpty(postdata))
{
rqst.ContentType = "application/x-www-form-urlencoded";

byte[] byteData = Encoding.UTF8.GetBytes(postdata);
rqst.ContentLength = byteData.Length;
using (Stream postStream = rqst.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
}
}
((HttpWebRequest)rqst).KeepAlive = false;
StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());
string strRsps = rsps.ReadToEnd();
return strRsps;
}

问题是,在调用 GetRequestStream 时,我不断收到 WebException 消息 “远程服务器返回错误:(502) Bad Gateway。”

一开始以为是SSL证书校验的问题。所以我添加了这一行:

ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

在哪里

public class AcceptAllCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint,
System.Security.Cryptography.X509Certificate certificate,
WebRequest request,
int certificateProblem)
{
return true;
}
}

而且我不断收到相同的 502 错误。有什么想法吗?

最佳答案

读取错误响应的实体主体。它可能会提示正在发生的事情。

执行此操作的代码如下:

catch(WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Response.Write(sr.ReadToEnd());
}
}
}

这应该显示错误响应的全部内容。

关于c# - 通过 SSL 使用 HttpWebRequest 发送请求时出现错误 502(错误的网关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2159361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com