• C#接口Post数据


     

     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         }
  • 相关阅读:
    iOS中多线程的实现方案
    初识多线程
    《文献管理与信息分析》第一讲学习总结
    《构建之法》第一章读书摘要
    Total Commander的初次体验
    学习《深入理解计算机系统》第一章摘要
    Vim编辑器的学习
    关于《文献管理与信息分析》的一些问题
    阅读《构建之法》后所产生的问题
    阅读《深入理解计算机系统(第三版)》产生的一些疑惑和困惑
  • 原文地址:https://www.cnblogs.com/yishilin/p/7742170.html
Copyright © 2020-2023  润新知