2017-07-18 94 views
0

我正在尝试使用使用CURL的vultr.com API。我已经成功地完成了一个POST调用,他们的API有几个不同的调用,但其中一个不能工作。这里是他们关于API https://www.vultr.com/api/的文档。C#API POST类似于CURL

我能够得到他们的服务器/创建和防火墙/ 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 + "\r\n\r\n'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..."); 
    } 
} 

它没有收到错误,但无法重新引导虚拟机。我已经联系他们的支持,他们说他们的重新启动命令没有任何问题。有没有人曾经遇到过这个问题?谢谢。

+0

执行此操作时是否有任何东西写入控制台? – mjwills

+0

'subId'的** exact **值是什么?此外,文档声称API密钥是必需的,但您的代码似乎没有设置它。 https://www.vultr.com/api/ – mjwills

+0

你如何确认VM不重启?你检查了虚拟机的状态吗?重新启动可能需要一些时间,它不会在一秒钟内完成。 –

回答

0

我想通了。有了我通过API完成的所有其他POST请求,需要使用Req.ContentLength = Data.Length行。但无论出于何种原因,必须删除该行才能使重新启动命令生效。