C# Post调用接口并传递json参数
1 public string Post(string Url, string jsonParas) 2 { 3 string strURL = Url; 4 //创建一个HTTP请求 5 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL); 6 //Post请求方式 7 request.Method = "POST"; 8 //内容类型 9 request.ContentType = "application/json"; 10 11 //设置参数,并进行URL编码 12 13 string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas); 14 15 byte[] payload; 16 //将Json字符串转化为字节 17 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); 18 //设置请求的ContentLength 19 request.ContentLength = payload.Length; 20 //发送请求,获得请求流 21 22 Stream writer; 23 try 24 { 25 writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象 26 } 27 catch (Exception) 28 { 29 writer = null; 30 Console.Write("连接服务器失败!"); 31 } 32 //将请求参数写入流 33 writer.Write(payload, 0, payload.Length); 34 writer.Close();//关闭请求流 35 // String strValue = "";//strValue为http响应所返回的字符流 36 HttpWebResponse response; 37 try 38 { 39 //获得响应流 40 response = (HttpWebResponse)request.GetResponse(); 41 } 42 catch (WebException ex) 43 { 44 response = ex.Response as HttpWebResponse; 45 } 46 Stream s = response.GetResponseStream(); 47 // Stream postData = Request.InputStream; 48 StreamReader sRead = new StreamReader(s); 49 string postContent = sRead.ReadToEnd(); 50 sRead.Close(); 51 return postContent;//返回Json数据 52 } 53 //调用: string askurl = testUrl + "?sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs; 54 //string relust = Post(askurl, ""); 55 // 或者 string relust = Post(askurl, sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs);
本文链接:https://blog.csdn.net/weixin_43343835/article/details/98959523