• 在服务端发起一个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.结果

  • 相关阅读:
    发送短信验证(防刷新)
    JsRender 学习总结
    JsRender (js模板引擎)
    jQuery中ready与load事件的区别
    web端图片文件直传
    2018面对对象_作业三
    2018面对对象_作业二
    2018面对对象_作业一
    2018寒假作业_4(自我总结)
    2018寒假作业_3(电梯版本二)
  • 原文地址:https://www.cnblogs.com/CallmeYhz/p/8602652.html
Copyright © 2020-2023  润新知