zoukankan      html  css  js  c++  java
  • Http请求代码

        public class HttpHelper
        {
            /// <summary>  
            /// 指定Post地址使用Get 方式获取全部字符串  
            /// </summary>  
            /// <param name="url">请求后台地址</param>  
            /// <returns></returns>  
            public static string HttpPost(string url, Dictionary<string, string> dic)
            {
                string result = "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                #region 添加Post 参数
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                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
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容  
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
    
    
            public static string HttpGet(string url)
            {
    
                string serviceAddress = url;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
        }
    

      

  • 相关阅读:
    记一次CTF出题WP
    markdown测试
    高强度学习训练第二天总结:Opencv+Android+CameraView小demo
    高强度学习训练第一天总结:Java内存区域
    黑客中最受欢迎的工具排行榜
    Java面试复习(纯手打)
    深度学习概论学习笔记
    TensorFlow、numpy、matplotlib、基本操作
    OpenCV 笔记
    Vue Stomp+SocketJS 数据报错[Object object]
  • 原文地址:https://www.cnblogs.com/Kuleft/p/11088207.html
Copyright © 2011-2022 走看看