C#后台发送Http请求

方式一

///
///
/// 1表示比特币,2表示莱特币
///
public string RequestHuoBiApi(string period, int type = 1)
{
string typeBcURL = "http://api.huobi.com/staticmarket/btc_kline_{0}_json.js?length=1000";          
System.Net.WebClient client = new System.Net.WebClient();
string url = string.Format(typeBcURL, period);
Task task = client.OpenReadTaskAsync(url);
System.IO.Stream backStream = task.Result;
System.IO.StreamReader reader = new System.IO.StreamReader(backStream);
string json = reader.ReadToEnd();
return json;
}

方式二

/// 发送请求
        ///
        /// 请求地址
        /// 参数格式 “name=王武&pass=123456”
        ///
        public static string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";
            try
            {
                System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
                httpRquest.Method = "POST";
                //这行代码很关键,不设置ContentType将导致后台参数获取不到值
                httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                //httpRquest.ContentLength = dataArray.Length;
                System.IO.Stream requestStream = null;
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    requestStream = httpRquest.GetRequestStream();
                    requestStream.Write(dataArray, 0, dataArray.Length);
                    requestStream.Close();
                }
                System.Net.WebResponse response = httpRquest.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return backMsg;
        }









你可能感兴趣的:(ASP.NET,MVC,C#)