zoukankan      html  css  js  c++  java
  • c#发送http请求注意

    这里要注意几个点:
    第一就是编码,如果编码不对,容易中文乱码
    第二就是ContentType 如果设置不对,有可能连方法都调试不进去(我api用的是MVC的普通controller)
    第三就是paramData参数形式要与ContentType保持一致

            /// <summary>
            /// 发送POST请求
            /// </summary>
            /// <param name="postUrl">api</param>
            /// <param name="paramData">参数,一般是param1=1&m2=2这种形式</param>
            /// <param name="dataEncode">编码</param>
            /// <returns></returns>
            private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
            {
                string ret = string.Empty;
                try
                {
                    byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                    webReq.Method = "POST";
                    webReq.ContentType = "application/x-www-form-urlencoded";
                    //webReq.ContentType = "application/json";
                    webReq.ContentLength = byteArray.Length;
                    Stream newStream = webReq.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                    HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                    StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    ret = sr.ReadToEnd();
                    sr.Close();
                    response.Close();
                    newStream.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                return ret;
            }
  • 相关阅读:
    MySQL ——索引原理与慢查询优化(Day45)
    mysql 练习题(Day44)
    MySQL 多表查询(Day43)
    MySQL 单表查询(Day42)
    MySQL -表完整性约束(Day41)
    回调函数
    进程池
    共享数据, 信号量(了解),事件(了解)
    管道
    python并发编程之多进程
  • 原文地址:https://www.cnblogs.com/tongdengquan/p/6288401.html
Copyright © 2011-2022 走看看