文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

C#使用Post调用接口并传递json参数

2024-04-02 19:55

关注

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯