關於C# winform怎麼調用webapi來獲取到json數據

C/S系統也能夠和B/S系統同樣實現「先後端分離」,那這樣寫winform就至關於純粹的前端頁面了,而後再單獨部署一個webapi項目,經過api調用數據庫進行數據的操做,有利於維護和數據安全性的提升,那麼winform怎麼去調用api接口呢,寫了一個demo,你們借鑑一下哈,本人才疏學淺,有不足和錯誤請指出:html

        winform界面就不設計了,僅僅是爲了測試是否調用到api,直接在建立的類庫中寫一個方法:前端

[csharp] view plain copy
  1.        /// <summary>  
  2.        /// 調用api返回json  
  3.        /// </summary>  
  4.        /// <param name="url">api地址</param>  
  5.        /// <param name="jsonstr">接收參數</param>  
  6.        /// <param name="type">類型</param>  
  7.        /// <returns></returns>  
  8.        public static string HttpApi(string url, string jsonstr, string type)  
  9.        {  
  10.            Encoding encoding = Encoding.UTF8;  
  11.            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest請求api地址  
  12.            request.Accept = "text/html,application/xhtml+xml,*/*";  
  13.            request.ContentType = "application/json";  
  14.            request.Method = type.ToUpper().ToString();//get或者post  
  15.            byte[] buffer = encoding.GetBytes(jsonstr);  
  16.            request.ContentLength = buffer.Length;  
  17.            request.GetRequestStream().Write(buffer, 0, buffer.Length);  
  18.            HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  19.            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))  
  20.            {  
  21.                return reader.ReadToEnd();  
  22.            }  
  23.        }  

而後再winform界面的事件中調用該方法:web

[csharp] view plain copy
  1. private void button3_Click(object sender, EventArgs e)  
  2.         {  
  3.             string url = "...(此處爲api端口)/api/VisitorInfo/GetEndVisitorInfoList";  
  4.             var str = ApiHelper.HttpApi(url, "{}""get");  
  5.         }  

本地運行後變量str接收數據格式以下:數據庫

HttpWebRequest請求時沒法發送具備此謂詞類型的內容正文。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl); //--須要封裝的參數
             request.CookieContainer = new CookieContainer();
             CookieContainer cookie = request.CookieContainer; //若是用不到Cookie,刪去便可 
             //如下是發送的http頭
             request.Referer = "" ;
             request.Accept = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" ;
             request.Headers[ "Accept-Language" ] = "zh-CN,zh;q=0." ;
             request.Headers[ "Accept-Charset" ] = "GBK,utf-8;q=0.7,*;q=0.3" ;
             request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1" ;
             request.KeepAlive = true ;
             //上面的http頭看狀況而定,可是下面倆必須加 
             request.ContentType = "application/x-www-form-urlencoded" ;
             Encoding encoding = Encoding.UTF8; //根據網站的編碼自定義
             request.Method = "get" //--須要將get改成post纔可行
             string postDataStr;
             Stream requestStream = request.GetRequestStream();
             if (postDatas != "" )
             {
                 postDataStr=postDatas; //--須要封裝,形式如「arg=arg1&arg2=arg2」
                 byte [] postData = encoding.GetBytes(postDataStr); //postDataStr即爲發送的數據,
                 request.ContentLength = postData.Length;
                 requestStream.Write(postData, 0, postData.Length);
             }
 
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             Stream responseStream = response.GetResponseStream();
 
 
             StreamReader streamReader = new StreamReader(responseStream, encoding);
             string retString = streamReader.ReadToEnd();
 
             streamReader.Close();
             responseStream.Close();
             return retString;

  若是是以流的方式提交表單數據的時候不能使用get方法,必須用post方法,json

改成
1
request.Method = "post" ;  就能夠了。  作一個記號

今天請求接口直接調了之前寫好的方法,結果報了(405)不支持方法的錯誤,一看是GET寫成POST了,改爲GET以後,又報了沒法發送具備此謂詞類型的內容正文錯誤的錯誤後端

原來以前的方法裏面有GetRequestStream(), GET請求並不支持它。api

把GetRequestStream()和相應的代碼註釋掉就OK了安全

      // Stream outStream = myRequest.GetRequestStream();
      // outStream.Write(arrB, 0, arrB.Length);
      //outStream.Close();

特此記錄!cookie

 

出處:https://blog.csdn.net/Andrewniu/article/details/79752653app

相關文章
相關標籤/搜索