我在使用 GET 方法向 C# 中的 API 发出 WebClient 请求时遇到此消息,我是否遗漏了代码中的某些内容?但是当我使用 POST 方法时,当我在 PostMan 上对其进行测试时,它会显示相同的输出,这是错误,因为 POST 不是在此链接中使用的方法
这是我的代码。
[WebMethod]
public string HelloWorld()
{
string module = "/heartbeat";
string method = "GET";
string link = sandboxURL;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // 3072 is SecurityProtocol.Tls12
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
var response = "";
string body = "";
var _link = link + module;
using (var client = new WebClient())
{
try
{
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Authorization", "Bearer "+ JWTToken);
//var url = new Uri(_link);
response = client.UploadString(_link, method, body);
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
var statusCode = (int)wrsp.StatusCode;
var msg = wrsp.StatusDescription;
Stream stream = wrsp.GetResponseStream();
byte[] data = new byte[4096];
int read;
StringBuilder sb = new StringBuilder();
while ((read = stream.Read(data, 0, data.Length)) > 0)
{
sb.Append(ASCIIEncoding.ASCII.GetString(data));
}
}
}
}
return response;
}