Beispiel #1
0
        public static ReturnValue StreamReader(string RequestURI, byte[] RequestData, Encoding Encode, bool Post)
        {
            System.Net.ServicePointManager.Expect100Continue = true;

            ReturnValue retValue = new ReturnValue();

            if (Encode == null)
            {
                Encode = System.Text.Encoding.GetEncoding("utf-8");
            }
            string         strReturnCode;
            HttpWebRequest myHttpWebRequest = null;

            //如果是发送HTTPS请求
            if (RequestURI.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(RequestURI);
                myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(RequestURI);
            }

            try
            {
                byte[] bs;
                if (Post)
                {
                    myHttpWebRequest.Method      = "POST";
                    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    bs = RequestData;

                    myHttpWebRequest.ContentLength = bs.Length;

                    using (Stream reqStream = myHttpWebRequest.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                    }
                }
                else
                {
                    myHttpWebRequest.Method = "GET";
                }
                using (WebResponse myWebResponse = myHttpWebRequest.GetResponse())
                {
                    StreamReader readStream = new StreamReader(myWebResponse.GetResponseStream(), Encode);
                    strReturnCode = readStream.ReadToEnd();
                }

                retValue.HasError     = false;
                retValue.Message      = strReturnCode;
                retValue.ReturnObject = null;
            }
            catch (Exception ex)
            {
                retValue.HasError     = true;
                retValue.Message      = "请求接口信息出错";
                retValue.ReturnObject = ex;
            }
            return(retValue);
        }