2016-07-08 134 views
1

我試圖做一個API調用工作來創建一個警報,但我不知道如何正確地做到這一點。它對我來說沒有什麼意義,所以我提供了下面我寫的代碼,但無法確定它爲什麼返回錯誤的請求錯誤。如何向OpsGenie發送POST請求?

這可能是因爲我的請求格式不正確或什麼,但我不能說,因爲我從來沒有做過任何與CURL做任何事情。

它應該張貼類似於一個捲曲的請求:

curl -XPOST 'https://api.opsgenie.com/v1/json/alert' -d ' 
{ 
    "apiKey": "eb243592-faa2-4ba2-a551q-1afdf565c889", 
     "message" : "WebServer3 is down", 
     "teams" : ["operations", "developers"] 
}' 

但它不工作。

電話功能:

OpsGenie.createAlert("1b9ccd31-966a-47be-92f2-ea589afbca8e", "Testing", null, null, new string[] { "ops_team" }, null, null); 

最後,它返回一個錯誤的請求。我不知道我是如何加入數據或任何東西,所以任何幫助將不勝感激。

public static void createAlert(string api, string message, string description, string entity, string[] teams, string user, string[] tags) 
    { 
     var request = WebRequest.Create(new Uri("https://api.opsgenie.com/v1/json/alert")); 
     string json = "{"; 
     if (api != null) 
      json = json + "'apiKey': '" + api + "'"; 
     if (message != null) 
      json = json + ", 'message': '" + message + "'"; 
     if (description != null) 
      json = json + ", 'description': '" + description + "'"; 
     if (entity != null) 
      json = json + ", 'entity': '" + entity + "'"; 
     if (teams != null) 
     { 
      json = json + ", 'teams': '['" + string.Join(",", teams) + "']'"; 
     } 
     if (user != null) 
      json = json + ", 'user': '" + user + "'"; 
     if (tags != null) 
      json = json + ", 'tags': '" + tags.ToString() + "'"; 
     json = json + "}"; 
     Console.WriteLine(json); 
     request.Method = "POST"; 
     try 
     { 
      using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
      { 
       streamWriter.Write(json); 
       streamWriter.Flush(); 
       streamWriter.Close(); 
      } 


      var httpResponse = (HttpWebResponse)request.GetResponse(); 
      using (var streamReader = new StreamReader(stream: httpResponse.GetResponseStream())) 
      { 
       var result = streamReader.ReadToEnd(); 
       dynamic obj = JsonConvert.DeserializeObject(result); 
       var messageFromServer = obj.error.message; 
       Console.WriteLine(messageFromServer); 

      } 
     } 
     catch (WebException e) 
     { 
      if (e.Status == WebExceptionStatus.ProtocolError) 
      { 
       Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); 
       Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); 
      } 
      else 
      { 
       Console.WriteLine(e.Message); 
      } 

     } 
    } 

回答

2

對於這樣的任務,使用WebClient可能會更容易。它有很多幫助方法,使得像字符串一樣下載和上傳內容非常簡單。

另外,不要試圖通過連接字符串來構建JSON有效載荷,只需使用Newtonsoft.Json即可。

我重構了使用WebClientJsonConvert的方法。現在更簡單了!我將調試留在原地,但是您可以在測試後刪除控制檯日誌記錄行:

public static void CreateAlert(string api, string message, string description, string entity, string[] teams, 
    string user, string[] tags) 
{ 
    // Serialize the data to JSON 
    var postData = new 
    { 
     apiKey = api, 
     message, 
     teams 
    }; 
    var json = JsonConvert.SerializeObject(postData); 

    // Set up a client 
    var client = new WebClient(); 
    client.Headers.Add("Content-Type", "application/json"); 

    try 
    { 
     var response = client.UploadString("https://api.opsgenie.com/v1/json/alert", json); 
     Console.WriteLine("Success!"); 
     Console.WriteLine(response); 
    } 
    catch (WebException wex) 
    { 
     using (var stream = wex.Response.GetResponseStream()) 
     using (var reader = new StreamReader(stream)) 
     { 
      // OpsGenie returns JSON responses for errors 
      var deserializedResponse = JsonConvert.DeserializeObject<IDictionary<string, object>>(reader.ReadToEnd()); 
      Console.WriteLine(deserializedResponse["error"]); 
     } 
    } 
}