static void Main(string[] args)
{
string str = "hello";
/*
* 注意这里的链接,要加上.json
* 我就是在这里被坑了1个小时
* 总是异常:400 Bad Request
* 之后我在野狗云应用中手动加入了一个user节点
* 然后就正常保存了
*/
//appId:对应你的野狗云应用
Post("https://<appId>.wilddogio.com/user.json", "{\"col1\":\"" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\",\"col2\":\"" + str + "\"}");
}
/// <summary>
/// 发送post请求
/// </summary>
/// <param name="posturl">请求地址</param>
/// <param name="jsonstr">json数据</param>
/// <returns></returns>
public static string Post(string posturl, string jsonstr)
{
//设置https验证方式
if (posturl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateva lidationCallback =
new RemoteCertificateva lidationCallback(CheckValidationResult);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(posturl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//json字符串转为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonstr);
//设置请求的ContentLength
request.ContentLength = bytes.Length;
//发送请求,获得请求流
Stream stream;
try
{
//获取用于写入请求数据的Stream对象
stream = request.GetRequestStream();
}
catch (Exception ex)
{
stream = null;
Console.WriteLine(ex.Message);
}
//把数据写入流
stream.Write(bytes, 0, bytes.Length);
stream.Close();
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
string strVal = sr.ReadToEnd().Trim();
sr.Close();
s.Close();
return strVal;
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}