C# API 帖子类似于 CURL



我正在尝试使用利用CURL的 vultr.com API。 我已经通过几个不同的调用成功完成了对他们的 API 的 POST 调用,但特别是一个不起作用。 这是他们在 API https://www.vultr.com/api/上的文档。

我能够让他们的服务器/创建和防火墙/rule_create使用几乎完全相同的代码正常工作,但它不适用于他们的服务器/重新启动命令。 现在,这是我已成功开始工作的他们的API帖子的代码。

public static void AddIpToFirewall(string ip,string fireWallGroupId)
{
string Data = "FIREWALLGROUPID=" + fireWallGroupId + "&direction=in&ip_type=v4&protocol=tcp&subnet=" + ip + "&subnet_size=32&port=80";
string Reponse = String.Empty;
StreamWriter Sw = null;
StreamReader Sr = null;
try
{
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://api.vultr.com/v1/firewall/rule_create");
Req.Method = "POST";
Req.ContentType = "application/x-www-form-urlencoded";
Req.ContentLength = Data.Length;
Req.Headers.Add(ApiKey);
using (var sw = new StreamWriter(Req.GetRequestStream()))
{
sw.Write(Data);
}
Sr = new
StreamReader(((HttpWebResponse)Req.GetResponse()).GetResponseStream());
Reponse = Sr.ReadToEnd();
Sr.Close();
}
catch (Exception ex)
{
if (Sw != null)
Sw.Close();
if (Sr != null)
Sr.Close();
Console.WriteLine(ex.Message + "rnrn'error with vultr...");
}
}

现在这是不起作用的代码。 它与防火墙 POST 命令几乎相同。

public static void RebootCommand(string subId)
{
string Data = "SUBID=" + subId;
string Reponse = String.Empty;
StreamWriter Sw = null;
StreamReader Sr = null;
try
{
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://api.vultr.com/v1/server/reboot");
Req.Method = "POST";
Req.ContentType = "application/x-www-form-urlencoded";
Req.ContentLength = Data.Length;
Req.Headers.Add(ApiKey);
using (var sw = new StreamWriter(Req.GetRequestStream()))
{
sw.Write(Data);
}
Sr = new
StreamReader(((HttpWebResponse)Req.GetResponse()).GetResponseStream());
Reponse = Sr.ReadToEnd();
Sr.Close();
}
catch (Exception ex)
{
if (Sw != null)
Sw.Close();
if (Sr != null)
Sr.Close();
Console.WriteLine(ex.Message + " error with vultr...");
}
}

它不会收到错误,但无法重新启动 VM。 我已经联系了他们的支持,他们说他们的重新启动命令可以正常工作。 以前有没有人遇到过这个问题? 谢谢。

我想通了。 对于我从他们的API完成的所有其他POST请求,Req.ContentLength = Data.Length行是必需的。 但是无论出于何种原因,都必须删除该行才能使重新启动命令正常工作。

最新更新