C#調用接口注意要點

在用C#調用接口的時候,遇到須要經過調用登陸接口才能調用其餘的接口,由於在其餘的接口須要在登陸的狀態下保存Cookie值纔能有權限調用,json

因此首先須要經過調用登陸接口來保存cookie值,再進行其餘接口的調用瀏覽器

1.經過Get方式服務器

#region get方式

        public string HttpGet(string url) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "application/json"; request.Headers["Accept-Encoding"] = "gzip,deflase"; request.AutomaticDecompression = DecompressionMethods.GZip; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // HttpCookie cookies = new HttpCookie("admin"); //若是有須要經過登陸實現保存cookie值的話能夠加一部分 // cookies.Value = Convert.ToString(response.Headers["Set-Cookie"]); // 經過響應請求讀取帶cookie的http數據 // cookies.Expires = DateTime.Now.AddDays(1); // HttpContext.Current.Response.Cookies.Add(cookies);

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } #endregion

 

可是並非全部的get請求都須要添加這個heard的內容,有些加了這個可能出現亂碼的狀況,因此不要設置Accept-Encoding的Headercookie

此處之因此加此header,是由於看到網頁分析工具中所獲得的瀏覽器瀏覽該網頁,對應的http的header的內容中,就是這樣設置的。app

因此,代碼中,也是模擬瀏覽器去訪問網頁,就設置了對應的Accept-Encoding爲gzip,deflate了工具

普通瀏覽器訪問網頁,之因此添加:"Accept-Encoding" = "gzip,deflate"post

那是由於,瀏覽器對於從服務器中返回的對應的gzip壓縮的網頁,會自動解壓縮,因此,其request的時候,添加對應的頭,代表本身接受壓縮後的數據。測試

同時添加了 request.AutomaticDecompression = DecompressionMethods.GZip;這一句,即可以得到正確的數據。編碼

若是你獲取網頁內容太大的話,那麼仍是能夠用這個辦法的,這樣就可讓HttpWebRequest自動幫你實現對應的解壓縮了,能夠減小數據數據傳輸量,節省時間,提升效率。url

2.經過post方式

public string HttpPost2(string url, string body) { //把用戶傳過來的數據轉成「UTF-8」的字節流
    Encoding encoding = Encoding.UTF8; //先根據用戶請求的uri構造請求地址 //建立Web訪問對象
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.Method = "POST"; // request.Accept = "application/json";
   request.ContentType = "application/json; charset=UTF-8"; request.Headers["Accept-Encoding"] = "gzip, deflate"; request.AutomaticDecompression = DecompressionMethods.GZip; //HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies["admin"]; //如果須要登陸事後再能訪問獲取url的數據,須要在請求頭中設置cookie值 //if (Cookie != null) // request.Headers.Add("Cookie", Cookie.Value.ToString());

   byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); //經過Web訪問對象獲取響應內容
   HttpWebResponse response = (HttpWebResponse) request.GetResponse(); //經過響應內容流建立StreamReader對象,由於StreamReader更高級更快
   using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd();//利用StreamReader就能夠從響應內容從頭讀到尾
 } }

3.經過put請求

 #region Put請求
        public string Put(string data, string uri) {//建立Web訪問對象
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(uri); //把用戶傳過來的數據轉成「UTF-8」的字節流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); Request.Method = "PUT"; Request.ContentLength = buf.Length; Request.ContentType = "application/json"; Request.MaximumAutomaticRedirections = 1; Request.AllowAutoRedirect = true; //發送請求
            Stream stream = Request.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //獲取接口返回值 //經過Web訪問對象獲取響應內容
            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //經過響應內容流建立StreamReader對象,由於StreamReader更高級更快
            StreamReader reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8); //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//若是有編碼問題就用這個方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就能夠從響應內容從頭讀到尾
 reader.Close(); Response.Close(); return returnXml; } #endregion

4.經過Delete請求

 #region Delete請求
        public string Delete(string data, string uri) { //建立Web訪問對象
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(uri); //把用戶傳過來的數據轉成「UTF-8」的字節流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); Request.Method = "DELETE"; Request.ContentLength = buf.Length; Request.ContentType = "application/json"; Request.MaximumAutomaticRedirections = 1; Request.AllowAutoRedirect = true; //發送請求
            Stream stream = Request.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); //獲取接口返回值 //經過Web訪問對象獲取響應內容
            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //經過響應內容流建立StreamReader對象,由於StreamReader更高級更快
            StreamReader reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8); //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//若是有編碼問題就用這個方法
            string returnXml = reader.ReadToEnd();//利用StreamReader就能夠從響應內容從頭讀到尾
 reader.Close(); Response.Close(); return returnXml; } #endregion

不一樣的場景需求,使用不一樣的方式,應用在不一樣的場景 。

經過這幾種組合方式 ,能夠調用http接口,完成調用和測試。

相關文章
相關標籤/搜索