zoukankan      html  css  js  c++  java
  • 在服务端发起一个Post请求

    1.http://www.tuling123.com/openapi/api?key=9d2ff29d44b54e55acadbf5643569584&info=?

    上面这个请求在服务端发起

       /// <summary>
        /// 构造url的参数ajax的data值
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string GetUrlStr(Dictionary<string, string> dic) {
            StringBuilder sb = new StringBuilder();
            foreach (var item in dic) {
                sb.AppendFormat("{0}={1}&", item.Key, item.Value);
            }
            string urlStr = sb.Remove(sb.Length - 1, 1).ToString();
            return urlStr;
        }
    
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="postData"></param>
        /// <param name="postUrl"></param>
        /// <returns></returns>
        public static string SendHttpPostRequest(string postData,string postUrl) {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
            byte[] data = Encoding.GetEncoding("gbk").GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            using (Stream stream = request.GetRequestStream()) {
                stream.Write(data, 0, data.Length);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            return responseString;
        }

    2.将参数进行编码后调用

        protected void Page_Load(object sender, EventArgs e) {
            Dictionary<string, string> test = new Dictionary<string, string>();
            test.Add("info", System.Web.HttpUtility.UrlEncode("笑话"));
            string paream = Utility.GetUrlStr(test);       
            string result = Utility.SendHttpPostRequest(paream, "http://www.tuling123.com/openapi/api?key=9d2ff29d44b54e55acadbf5643569584");
            Response.Write(result);
        }

    3.结果

  • 相关阅读:
    测试爬虫
    流式大数据处理的三种框架:Storm,Spark和Samza
    redo日志
    HTTP协议之chunk编码(分块传输编码
    QWidget 实现 打破布局 或者 当前窗体内的 弹窗 (借助伪造实现)
    How to use kingshard building a MySQL cluster
    转载: Qt 学习之路 2归档
    Python与机器人技术
    Nginx配置正向代理
    使用Chrony配置 NTP
  • 原文地址:https://www.cnblogs.com/CallmeYhz/p/8602652.html
Copyright © 2011-2022 走看看