C# 发送Post请求(带参数)

时间:2025-03-10 09:51:18

此处内容传输都是用UTF-8编码

1.不带参数发送Post请求

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string Post(string url)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)(url);
             = "POST";
            HttpWebResponse resp = (HttpWebResponse)();
            Stream stream = ();
            //获取内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = ();
            }
            return result;
        }

2.带参数Post请求,指定键值对

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string Post(string url,Dictionary<string,string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)(url);
             = "POST";
             = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    ("&");
                ("{0}={1}", , );
                i++;
            }
            byte[] data = Encoding.(());
             = ;
            using (Stream reqStream = ())
            {
                (data, 0, );
                ();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)();
            Stream stream = ();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = ();
            }
            return result;
        }

3.带参数的Post请求,指定发送字符串内容

/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <param name="content">Post提交数据内容(utf-8编码的)</param>
/// <returns></returns>
public static string Post(string url, string content)
{
    string result = "";
    HttpWebRequest req = (HttpWebRequest)(url);
     = "POST";
     = "application/x-www-form-urlencoded";
 
    #region 添加Post 参数
    byte[] data = Encoding.(content);
     = ;
    using (Stream reqStream = ())
    {
        (data, 0, );
        ();
    }
    #endregion
 
    HttpWebResponse resp = (HttpWebResponse)();
    Stream stream = ();
    //获取响应内容
    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
    {
        result = ();
    }
    return result;
}

转载方法:

 HttpWebRequest req = (HttpWebRequest)("/transcontent");
            Encoding encoding = Encoding.UTF8;
            string param = "ie=utf-8&source=txt&query=hello&t=1327829764203&token=8a7dcbacb3ed72cad9f3fb079809a127&from=auto&to=auto";
            //(postData);
            byte[] bs = (param);
            string responseData = ;            
             = "POST";
             = "application/x-www-form-urlencoded";
             = ;
            using (Stream reqStream = ())
            {
                (bs, 0, );
                ();
            }
            using (HttpWebResponse response = (HttpWebResponse)())
            {
                using (StreamReader reader = new StreamReader((),encoding))
                {
                    responseData = ().ToString();
                }
                (responseData);
            }

4.发送get请求

 public static string Get(string Url)
        {
            //();
            HttpWebRequest request = (HttpWebRequest)(Url);
             = null;
             = false;
             = "GET";
             = "application/json; charset=UTF-8";
             = ;

            HttpWebResponse response = (HttpWebResponse)();
            Stream myResponseStream = ();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = ();

            ();
            ();

            if (response != null)
            {
                ();
            }
            if (request != null)
            {
                ();
            }

            return retString;
        }

5.发送json内容和header设置

 private void postjson()
    {
        string RobotID = ("RobotID");//header
        string phoneNumber = ("phoneNumber");
        int remainingTime_min = ("remainingTime_min", 0);

        string url = ":1800/Robot/WebDeviceInfo";
        //Hashtable hash_json = new Hashtable();
        //hash_json.Add("phoneNumber", phoneNumber);
        //hash_json.Add("remainingTime_min", remainingTime_min);


        string hash_json = "{\"phoneNumber\": \"" + phoneNumber + "\",\"remainingTime_min\": " + remainingTime_min + "}";

        Hashtable hash_header = new Hashtable();
        hash_header.Add("RobotID", RobotID);
        (PostJson(url, hash_json.ToString(), hash_header));
        ();
    }
    private string PostJson(string url, string postData, Hashtable headht = null)
    {
        //https的需要加着两行----------------
         = ;
         = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
        //------------------

        HttpWebRequest request = (HttpWebRequest)(url);
         = "POST";
         = "application/json;charset=UTF-8";
         = "application/json";

        #region headers设置
        if (headht != null)
        {
            foreach (DictionaryEntry item in headht)
            {
                ((), ());
            }
        }
        #endregion

        byte[] paramJsonBytes;
        paramJsonBytes = .(postData);
         = ;
        Stream writer;
        try
        {
            writer = ();
        }
        catch (Exception e)
        {
            writer = null;
            ("连接服务器失败:" + ());
            ();
        }
        (paramJsonBytes, 0, );
        ();
        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)();
        }
        catch (WebException ex)
        {
            response =  as HttpWebResponse;
        }
        Stream resStream = ();
        StreamReader reader = new StreamReader(resStream);
        string text = ();
        return text;
    }

6.腾讯文档里的用例:

private const string sContentType = "application/x-www-form-urlencoded";
        private const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        public static string Send(string data, string url)
        {
            return Send(("UTF-8").GetBytes(data), url);
        }

        public static string Send(byte[] data, string url)
        {
            Stream responseStream;
            HttpWebRequest request = (url) as HttpWebRequest;
            if (request == null)
            {
                throw new ApplicationException(("Invalid url string: {0}", url));
            }
            //  = sUserAgent;  
             = sContentType;
             = "POST";
             = ;
            Stream requestStream = ();
            (data, 0, );
            ();
            try
            {
                responseStream = ().GetResponseStream();
            }
            catch (Exception exception)
            {
                throw exception;
            }

            string str = ;
            using (StreamReader reader = new StreamReader(responseStream, ("UTF-8")))
            {
                str = ();
            }
            ();
            return str;
        }

方法调用:

 Hashtable hash = new Hashtable();
         u = islogin();
        if (u != null)
        {
            string page_url = ("page_url");
            WX_About wa = new WX_About();
            string access_token = wa.getaccess_token(1);
            string url = "/wxa/genwxashortlink?access_token=" + access_token;
            string returnStr = ("{\"page_url\": \"" + page_url + "\"}", url);
            errorclass errmode = <errorclass>(returnStr);
            if ( == 0)
            {
                hash["error"] = 0;
                hash["errorstr"] = "获取成功";
                hash["data"] = returnStr;
            }
            else
            {
                hash["error"] = 1;
                hash["data"] = returnStr;
                hash["errorstr"] = "获取失败";
            }
        }
        else
        {
            hash["error"] = -1;
            hash["errorstr"] = "请先登录";
        }
        ((hash));
        ();

传递参数: = "application/x-www-form-urlencoded";

 SortedDictionary<string, string> inputPara = new SortedDictionary<string, string>();
                            ("pid", "1017");
                            ("method", "app");
                            ("type", "alipay");
                            ("out_trade_no", orderno);
                            ("notify_url",  + "/pay_buyer_back_juhe.aspx");
                            ("return_url", "www");
                            ("name", "订单支付");
                            ("money", ());
                            ("clientip", );//
                            //("param", "order," + );
                            ("timestamp", getTimestamp_ten());
                            ("sign_type", "RSA");

                            Dictionary<string, string> sPara = new Dictionary<string, string>();
                            //过滤空值、sign与sign_type参数
                            sPara = (inputPara);
                            //获取待签名字符串
                            string preSignStr = (sPara);

                            string sign_get = Sign2(preSignStr, appkey_juhe, "utf-8");


                            ("sign", sign_get);

                            string prepayXml = Post("/api/pay/create", inputPara);
 private string Sign2(string dataToSign, string privateKey, string _input_charset)
    {
        //转换成适用于.Net的秘钥
        var netKey = RSAPrivateKeyJava2DotNet(privateKey);
        var rsa = new RSACryptoServiceProvider();
        (netKey);

        //签名返回
        using (var sha256 = new SHA256CryptoServiceProvider())
        {
            var signData = (Encoding.(dataToSign), sha256);
            return Convert.ToBase64String(signData);
        }



    }

 private string getTimestamp_ten()
    {
        long timestamp = (long)( - new DateTime(1970, 1, 1, 0, 0, 0, )).TotalSeconds;
        return ().Substring(0, 10);
    }
private string Post(string url, SortedDictionary<string, string> dic)
    {
        string postData = "";// "key1=value1&key2=value2";

        StringBuilder builder = new StringBuilder();
        int i = 0;
        foreach (var item in dic)
        {
            if (i > 0)
                ("&");
            ("{0}={1}", , (, Encoding.UTF8));//这个地方要进行编码,否则传不过去
            i++;
        }
        postData = ();


         = (SecurityProtocolType)3072;
        HttpWebRequest request = (HttpWebRequest)(url);
         = "POST";
         = "application/x-www-form-urlencoded";
         = ;

        StreamWriter requestWriter = new StreamWriter((), );
        (postData);
        ();

        HttpWebResponse response = (HttpWebResponse)();
        StreamReader responseReader = new StreamReader(());
        string responseData = ();
        ();
        ();

        (responseData);

        return responseData;
    }