接口调用

发布时间:2019-03-10  栏目:Python  评论:0 Comments

图片 1

/// <summary>
        /// 发起一个HTTP请求(以POST方式)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string param = "")
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 10000;
            request.AllowAutoRedirect = false;
            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;
            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();
                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }
            return responseStr;
        }

/// <summary>
        /// 发起一个HTTP请求(以GET方式)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            WebRequest myWebRequest = WebRequest.Create(url); 
            WebResponse myWebResponse = myWebRequest.GetResponse(); 
            Stream ReceiveStream = myWebResponse.GetResponseStream(); 
            string responseStr = "";
            if (ReceiveStream != null)
            {
                StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close(); 
            }
            myWebResponse.Close();
            return responseStr;
        }

图片 2

  

图片 3

图片 4

留下评论

网站地图xml地图