web api 二

时间:2022-03-11 00:49:31

public JsonResult PostReques() { //请求路径 string url = ":6972/api/values/UpdateName"; //定义request并设置request的路径 WebRequest request = WebRequest.Create(url); request.Method = "post"; //初始化request参数 string postData = "{SiteId: \"2\",Title : \"博客园首页\", Uri :\"www.cnblogs.com\" }"; //设置参数的编码格式,解决中文乱码 byte[] byteArray = Encoding.UTF8.GetBytes(postData); //设置request的MIME类型及内容长度 request.ContentType = "application/json"; request.ContentLength = byteArray.Length; //打开request字符流 Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //定义response为前面的request响应 WebResponse response = request.GetResponse(); //获取相应的状态代码 Console.WriteLine(((HttpWebResponse)response).StatusDescription); //定义response字符流 dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();//读取所有 return new JsonResult() { Data = responseFromServer};