我正在使用jQuery进行休息。
$.ajax({
url: 'https://graylogurl/gelf',
dataType: 'json',
data: '{"short_message":"test message", "host":"localhost", "facility":"ajax", "_environment":"dev", "_meme":"yolo", "full_message":"this will contain a longer message"}',
type: 'POST'
});
这篇文章正确适用于我需要的内容。我尝试使用C#
在我的MVC4控制器中做类似的事情var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://graylogurl/gelf");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = false;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"short_message\":\"test message\", \"host\":\"localhost\", \"facility\":\"ajax\", \"_environment\":\"dev\", \"_meme\":\"yolo\", \"full_message\":\"this is from the controller\"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
不幸的是,它总是超时。不确定我做错了什么。
答案 0 :(得分:0)
尝试更换:
httpWebRequest.ContentType = "text/json";
使用正确的内容类型:
httpWebRequest.ContentType = "application/json";
还要确保在using
语句中包含了IDisposable资源,并使用WebClient
和正确的JSON序列化程序来构建您的JSON字符串似乎更容易,更正确:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var data = new JavaScriptSerializer().Serialize(new
{
short_message = "test message",
host = "localhost",
facility = "ajax",
_environment = "dev",
_meme = "yolo",
full_message = "this is from the controller",
});
var resultData = client.UploadData("https://graylogurl/gelf", Encoding.UTF8.GeBytes(data));
string result = Encoding.UTF8.GetString(resultData);
}
还要确保您托管ASP.NET应用程序的服务器可以访问您尝试访问的远程URL,并且没有防火墙阻止它。如果您有疑问,请联系您的网络管理员,但为了能够执行此HTTP请求,必须可以通过443端口(HTTPS)从托管您的应用程序的Web服务器访问远程URL。