1. 程式人生 > >C#呼叫URL介面方法

C#呼叫URL介面方法

第一種方法:

第一步:獲取在Web.config中配置要請求的地址
string url = System.Web.Configuration.WebConfigurationManager.AppSettings["url"];
第二步:把字串編碼(編碼詳解)
 string allStr = System.Web.HttpUtility.UrlEncode(str, System.Text.Encoding.UTF8) ;
第三步:把引數轉成byte 
 byte[] bufferB = Encoding.UTF8.GetBytes(allStr);
第四步:構建HttpWebRequest,併發送
System.Net.ServicePointManager.DefaultConnectionLimit = 200;
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = allStr.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(bufferB, 0, bufferB.Length);
PostData.Close();
第五步:接收返回結果(解析返回的JSON)
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
StreamReader sr = new StreamReader(WebResp.GetResponseStream(), System.Text.Encoding.UTF8);
string backstr = sr.ReadToEnd();
backstr = HttpUtility.UrlDecode(backstr);
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Console.WriteLine(_Answer.ReadToEnd());

第二種方法:

第一步---構建HttpWebRequest
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);               
WebReq.ContentType = "application/json";
WebReq.Method = Method;
第二步--寫入引數
 WebReq.ContentLength = Encoding.UTF8.GetByteCount(param);
 using (StreamWriter requestW = new StreamWriter(WebReq.GetRequestStream()))
                     {
                         requestW.Write(param);
                     }
第三步--獲取返回的結果
string backstr = null;
using (HttpWebResponse response = (HttpWebResponse)WebReq.GetResponse())
                {
                    StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                    backstr = sr.ReadToEnd();
                }

第三種通用:

public static string MakeRequest(string url, string query_string, string cookie_string, string method, string protocol)
        {
            //cookie
            //string cookie_string = null;
            //if (cookie != null && cookie.Count > 0)
            //{
            //    string[] arr_cookies = new string[cookie.Count];
            //    int i = 0;
            //    foreach (string key in cookie.Keys)
            //    {
            //        arr_cookies[i] = key + "=" + cookie[key];
            //        i++;
            //    }
            //    cookie_string = string.Join("; ", arr_cookies);
            //}
            //結果
            string result = "";
            //請求類
            HttpWebRequest request = null;
            //請求響應類
            HttpWebResponse response = null;
            //響應結果讀取類
            StreamReader reader = null;
            //http連線數限制預設為2,多執行緒情況下可以增加該連線數,非多執行緒情況下可以註釋掉此行程式碼
            ServicePointManager.DefaultConnectionLimit = 500;
            try
            {
                if (method.Equals("get", StringComparison.OrdinalIgnoreCase))
                {


                    if (url.IndexOf("?") > 0)
                    {
                        url = url + "&" + query_string;
                    }
                    else
                    {
                        url = url + "?" + query_string;
                    }
                    //如果是傳送HTTPS請求   
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    request.Method = "GET";
                    request.Timeout = 30000;
                }
                else
                {
                    //如果是傳送HTTPS請求   
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    //去掉“Expect: 100-Continue”請求頭,不然會引起post(417) expectation failed
                    ServicePointManager.Expect100Continue = false;


                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Timeout = 30000;
                    //POST資料   
                    byte[] data = Encoding.UTF8.GetBytes(query_string);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                //cookie
                if (!string.IsNullOrEmpty(cookie_string))
                {
                    request.Headers.Add("Cookie", cookie_string);
                }
                //response
                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                //return
                result = reader.ReadToEnd();
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return result;
        }

--轉自 http://blog.csdn.net/lijingrong_ljr/article/details/53214729