1 /// <summary> 2 /// 上传数据 3 /// </summary> 4 /// <param name="UserId"></param> 5 /// <param name="PageId"></param> 6 /// <param name="UserName"></param> 7 /// <param name="Comment"></param> 8 /// <param name="CommentTime"></param> 9 public static string PostData(int UserId, int PageId, string Comment, DateTime CommentTime) 10 { 11 string postData = "{"key":"*******","articleId": "" + PageId.ToString() + "" ,"userId": "" + UserId.ToString() + "" ,"creationTime": "" + CommentTime.ToString() + "" ,"content":"" + Comment + ""}"; 12 13 string posturl = "http://localhost:37831/api/Values"; 14 15 Stream outstream = null; 16 Stream instream = null; 17 StreamReader sr = null; 18 HttpWebResponse response = null; 19 HttpWebRequest request = null; 20 Encoding encoding = Encoding.UTF8; 21 byte[] data = encoding.GetBytes(postData); 22 // 准备请求... 23 try 24 { 25 // 设置参数 26 request = WebRequest.Create(posturl) as HttpWebRequest; 27 CookieContainer cookieContainer = new CookieContainer(); 28 request.CookieContainer = cookieContainer; 29 request.AllowAutoRedirect = true; 30 request.Method = "POST"; 31 request.ContentType = "application/json";//x-www-form-urlencoded"; 32 request.ContentLength = data.Length; 33 outstream = request.GetRequestStream(); 34 outstream.Write(data, 0, data.Length); 35 outstream.Close(); 36 //发送请求并获取相应回应数据 37 response = request.GetResponse() as HttpWebResponse; 38 //直到request.GetResponse()程序才开始向目标网页发送Post请求 39 instream = response.GetResponseStream(); 40 sr = new StreamReader(instream, encoding); 41 ////返回结果网页(html)代码 42 //string content = sr.ReadToEnd(); 43 string err = string.Empty; 44 return err; 45 } 46 catch (Exception ex) 47 { 48 string err = ex.Message; 49 return err; 50 } 51 }