C#使用Post调用接口并传递json参数
更新时间:2022年06月09日 09:52:17 作者:colouful_2021
这篇文章主要介绍了C#使用Post调用接口并传递json参数,具有很好的参考价值,希望对大家有所帮助。
Post调用接口并传递json参数
public string Post(string Url, string jsonParas) { string strURL = Url; //创建一个HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL); //Post请求方式 request.Method = "POST"; //内容类型 request.ContentType = "application/json"; //设置参数,并进行URL编码 string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas); byte[] payload; //将Json字符串转化为字节 payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); //设置请求的ContentLength request.ContentLength = payload.Length; //发送请求,获得请求流 Stream writer; try { writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象 } catch (Exception) { writer = null; Console.Write("连接服务器失败!"); } //将请求参数写入流 writer.Write(payload, 0, payload.Length); writer.Close();//关闭请求流 // String strValue = "";//strValue为http响应所返回的字符流 HttpWebResponse response; try { //获得响应流 response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; } Stream s = response.GetResponseStream(); // Stream postData = Request.InputStream; StreamReader sRead = new StreamReader(s); string postContent = sRead.ReadToEnd(); sRead.Close(); return postContent;//返回Json数据 } //调用: string askurl = testUrl + "?sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs; //string relust = Post(askurl, ""); // 或者 string relust = Post(askurl, sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs);
Post请求参数(发送Json参数、发送普通参数)
1.发送Json格式的Post请求
(1)Post调用
string PostUrl="http://IP:端口/AAA/BBB/CCC"; string id="123"; string Name="小黑"; JObject patientinfo = new JObject(); JArray ids = new JArray(); ids.Add(id); patientinfo["ids"] = ids; patientinfo["Name"] = Name; string sendData = JsonConvert.SerializeObject(patientinfo); //eg: 发送Url需要的格式:sendData={"ids":[123],"Name":小黑} string resultData = Post(sendData, PostUrl);
(2)Post方法
#region Post请求 /// <summary> /// http Post请求 /// </summary> /// <param name="parameterData">参数</param> /// <param name="serviceUrl">访问地址</param> /// <param name="ContentType">默认 application/json , application/x-www-form-urlencoded,multipart/form-data,raw,binary </param> /// <param name="Accept">默认application/json</param> /// <returns></returns> public string Post(string parameterData, string serviceUrl, string ContentType = "application/json", string Accept = "application/json") { //先根据用户请求的uri构造请求地址 //string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri); //创建Web访问对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); //把用户传过来的数据转成“UTF-8”的字节流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(parameterData); myRequest.Method = "POST"; //myRequest.Accept = "application/json"; //myRequest.ContentType = "application/json"; // //Content-Type: application/x-www-form-urlencoded myRequest.AutomaticDecompression = DecompressionMethods.GZip; myRequest.Accept = Accept; //myRequest.ContentType = ContentType; myRequest.ContentType = "application/json; charset=UTF-8"; myRequest.ContentLength = buf.Length; myRequest.MaximumAutomaticRedirections = 1; myRequest.AllowAutoRedirect = true; //myRequest.Headers.Add("content-type", "application/json"); //myRequest.Headers.Add("accept-encoding", "gzip"); //myRequest.Headers.Add("accept-charset", "utf-8"); //发送请求 Stream stream = myRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //通过Web访问对象获取响应内容 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法 string returnData = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾 reader.Close(); myResponse.Close(); return returnData; } #endregion
2.带参数的Post请求
(1)Post调用
string PostUrl="http://IP:端口/AAA/BBB/CCC"; Dictionary<string, string> dic=new Dictionary<string, string>(); dic.Add("Id","123"); dic.Add("Name","笑笑"); string resultData = Post(dic, PostUrl);
(2)Post方法
#region post带参数的请求 /// <summary> /// 指定Post地址使用Get 方式获取全部字符串 /// Post是从服务器上传送数据 /// </summary> /// <param name="url">请求Url地址</param> /// <param name="dic">拼接Url的字段</param> /// <returns></returns> public static string Post(string url, Dictionary<string, string> dic) { #region 【网上查的】 //eg:http://IP:端口/AAA/BBB/CCC//发送对应参数 #region 创建Web访问对象 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //req.Method = "POST"; //req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; req.AutomaticDecompression = DecompressionMethods.GZip; req.ContentType = "application/json; charset=UTF-8"; #endregion #region Post添加并拼接参数,形成对应Url地址 StringBuilder builder = new StringBuilder(); int i = 0; if (dic.Count > 0) { foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } } #endregion #region 发送请求 byte[] data = Encoding.UTF8.GetBytes(builder.ToString()); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } #endregion #region 通过Web访问对象获取响应内容 string result = ""; HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; #endregion #endregion } #endregion
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
深入Unix时间戳与C# DateTime时间类型互换的详解
本篇文章是对Unix时间戳与C# DateTime时间类型互换进行了详细的分析介绍,需要的朋友参考下2013-06-06
最新评论