跨域访问接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010082526/article/details/84675325

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URL);//HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得【跨域访问】

/// <summary>
        /// 根据第三方接口接收返回的数据
        /// </summary>
        /// <param name="urlPath">请求的地址</param>
        /// <returns></returns>
        public string GetHTTPInfo(string urlPath)
        {
            string str = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlPath);
                request.Timeout = 60000;
                request.Method = "Get";
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                str = reader.ReadToEnd();
            }
            catch
            {
                str = "";
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return str;
        }

猜你喜欢

转载自blog.csdn.net/u010082526/article/details/84675325