首页 > 代码库 > 使用HttpWebRequest方式访问外部接口

使用HttpWebRequest方式访问外部接口

第一步,如果不是http网站,则需认证信托证书

        /// <summary>        /// 认证信托证书        /// </summary>        /// <param name="sender"></param>        /// <param name="cert"></param>        /// <param name="chain"></param>        /// <param name="error"></param>        /// <returns></returns>        public static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)        {            LogHelper.WriteInfo("Warning, trust any certificate");            return true;        }

第二步,文字中文信息转成UTF-8格式

     /// <summary>        /// 把中文转换成UTF-8         /// </summary>        /// <param name="str"></param>        /// <returns></returns>        public static string UrlEncode(string str)        {            byte[] utf8 = Encoding.UTF8.GetBytes(str);            string s = "";            foreach (byte b in utf8)            {                s += string.Format("%{0:X2}", b);            }            return s;        }

第三步,使用HttpRequest方式访问指定Url

     /// <summary>        /// 使用HttpRequest方式访问Url        /// </summary>        /// <param name="url"></param>        /// <returns></returns>        public static string CreateHttpRequest(string url)        {            try            {                //创建HttpWebRequest请求连接                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);                //获取HttpResponse响应                HttpWebResponse response = (HttpWebResponse)request.GetResponse();                Stream stream = null;                StreamReader reader = null;                string strLine = string.Empty;                string strResponse = string.Empty;                //判断请求是否正常                if (response.StatusCode == HttpStatusCode.OK)                {                    stream = response.GetResponseStream();                    reader = new StreamReader(stream, Encoding.UTF8);                    //逐行读取                    while ((strLine = reader.ReadLine()) != null)                    {                        strResponse += strLine + "\r\n";                    }                }            }            catch (Exception e)            {                LogHelper.WriteError(e.Message, e);            }            return strResponse;        }

 

使用HttpWebRequest方式访问外部接口