我正在尝试进行API调用以创建警报,但我不确定如何正确执行。它对我来说没有多大意义所以我提供了下面的代码,但我无法理解为什么它会返回Bad Request错误。
可能是我的请求格式不正确或者其他什么,但我无法分辨,因为我之前从未做过任何与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);
}
}
}
答案 0 :(得分:3)
将WebClient
用于此类任务可能更容易。它有许多辅助方法,可以很容易地下载和上传字符串等内容。
此外,不要尝试通过连接字符串来构建JSON有效内容,只需使用Newtonsoft.Json。
我重构了您使用WebClient
和JsonConvert
的方法。现在它变得更简单了!我将调试保留在原位,但您可以在测试后删除控制台记录行:
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"]);
}
}
}
答案 1 :(得分:0)
由于API v1现已弃用,因此上述解决方案应如下所示:
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");
client.Headers.Add("Authorization", $"GenieKey {api}");
try
{
var response = client.UploadString("https://api.opsgenie.com/v2/alerts", 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"]);
}
}
}