1. 程式人生 > 實用技巧 >ASP.NET獲取線上介面資料HttpGet

ASP.NET獲取線上介面資料HttpGet

哈嘍,筒子們。又是令人開心的週六

忙碌(搬磚)的一週又過去了,讓我們來看一下今天要寫點什麼吧

首先介面API相信入行多年的選手都不陌生了,你呼叫我,我呼叫你,拿來拿去是很熟悉的都。

那麼今天來寫點關於呼叫介面獲取Json資料的內容吧【HTTPGET】

首先呼叫對方地址這個是肯定有的了,那麼怎麼安全的獲取到資料呢。

直接上方法。

   private string GetDataJsonBy(string url)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp 
= (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); try { //獲取內容 using (StreamReader reader = new StreamReader(stream)) { result = reader.ReadToEnd(); } }
finally { stream.Close(); } return result; }

HttpWebRequest和HttpWebResponse類是用於傳送和接收HTTP資料的最好選擇。它們支援一系列有用的屬性。這兩個類位 於System.Net名稱空間,預設情況下這個類對於控制檯程式來說是可訪問的。請注意,HttpWebRequest物件不是利用new關鍵字通過構 造函式來建立的,而是利用工廠機制(factory mechanism)通過Create()方法來建立的。另外,你可能預計需要顯式地呼叫一個“Send”方法,實際上不需要。接下來呼叫 HttpWebRequest.GetResponse()方法返回的是一個HttpWebResponse物件。你可以把HTTP響應的資料流(stream)繫結到一個StreamReader物件,然後就可以通過ReadToEnd()方法把整個HTTP響應作為一個字串取回。也可以通過StreamReader.ReadLine()方法逐行取回HTTP響應的內容。

上面這段說的應該是比較清楚了,那這個Create方法裡面具體是怎麼做的呢?一起來八一八原始碼

        // Create - Create a WebRequest.
        //
        // An overloaded utility version of the real Create that takes a
        // string instead of an Uri object.
        //
        // Input:
        //     RequestString       - Uri string to create.
        //
        // Returns:
        //     Newly created WebRequest.
        [Obsolete(Obsoletions.WebRequestMessage, DiagnosticId = Obsoletions.WebRequestDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
        public static WebRequest Create(string requestUriString)
        {
            if (requestUriString == null)
            {
                throw new ArgumentNullException(nameof(requestUriString));
            }
 
            return Create(new Uri(requestUriString), false);
        }
 

我們看到了,C#的原始碼做的還是很好的,在最新版裡面這個方法已經是被Obsolete了的。

不過不影響我們看它的實現,看看它內部呼叫的Create過載是怎麼寫的

        // Create a WebRequest.
        //
        // This is the main creation routine. We take a Uri object, look
        // up the Uri in the prefix match table, and invoke the appropriate
        // handler to create the object. We also have a parameter that
        // tells us whether or not to use the whole Uri or just the
        // scheme portion of it.
        //
        // Input:
        //     requestUri - Uri object for request.
        //     useUriBase - True if we're only to look at the scheme portion of the Uri.
        //
        // Returns:
        //     Newly created WebRequest.
        private static WebRequest Create(Uri requestUri, bool useUriBase)
        {
            string LookupUri;
            WebRequestPrefixElement? Current = null;
            bool Found = false;
 
            if (!useUriBase)
            {
                LookupUri = requestUri.AbsoluteUri;
            }
            else
            {
                // schemes are registered as <schemeName>":", so add the separator
                // to the string returned from the Uri object
                LookupUri = requestUri.Scheme + ':';
            }
 
            int LookupLength = LookupUri.Length;
 
            // Copy the prefix list so that if it is updated it will
            // not affect us on this thread.
 
            List<WebRequestPrefixElement> prefixList = PrefixList;
 
            // Look for the longest matching prefix.
 
            // Walk down the list of prefixes. The prefixes are kept longest
            // first. When we find a prefix that is shorter or the same size
            // as this Uri, we'll do a compare to see if they match. If they
            // do we'll break out of the loop and call the creator.
 
            for (int i = 0; i < prefixList.Count; i++)
            {
                Current = prefixList[i];
 
                // See if this prefix is short enough.
 
                if (LookupLength >= Current.Prefix.Length)
                {
                    // It is. See if these match.
                    if (string.Compare(Current.Prefix,
                                       0,
                                       LookupUri,
                                       0,
                                       Current.Prefix.Length,
                                       StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // These match. Remember that we found it and break
                        // out.
                        Found = true;
                        break;
                    }
                }
            }
 
            if (Found)
            {
                // We found a match, so just call the creator and return what it does.
                WebRequest webRequest = Current!.Creator.Create(requestUri);
                return webRequest;
            }
 
            // Otherwise no match, throw an exception.
            throw new NotSupportedException(SR.net_unknown_prefix);
        }

瞧瞧人家這個程式碼寫的,這命名,這質量,這注釋。

再瞧瞧我們的專案,誒~(露頭會被打死)

原始碼已貼

後面的程式碼你們自己扒拉吧,不貼了。【我才不會說我看不懂了】

    [HttpGet]
        public IHttpActionResult GetPersonnel()
        {
            DateTime startDay = new DateTime(2019, 5, 1);
            DateTime endDay = new DateTime(2019, 5, 2);
            TimeSpan leftTime =  new DateTime(2020, 12, 1)- startDay;
            int leftDay = Convert.ToInt32(leftTime.TotalDays);
            #region Info

            for (int i = 0; i < leftDay; i++)
            {
                string uri = "http://main.demo.com/api/personnel/getdemo?beginDate="+startDay.AddDays(i)+"&endDate=" + endDay.AddDays(i);

                string resultJson = GetDataJsonBy(uri);
                IList<Demo> data = JsonConvert.DeserializeObject<List<Demo>>(resultJson);

                foreach (var item in data)
                {
                    Demo entity = Demo.GetList(new { DataId = item.id }.ToJson()).FirstOrDefault();
                   
                    if (entity == null)
                    {//save new。
                        demo.SaveForm("", new nhw_EmployeesEntity{
              entityData.Mail = item.mailAddress,
                        entityData.Photo = item.picture
              }
);
continue; } entity.Mail = item.mailAddress; entity.Photo = item.picture; demo.SaveForm(entity.ID.ToString(), entity); } } #endregion return Json(""); }

拋磚引玉,我這裡只是貼了一個簡單的方法去獲取到資料,並且進行了資料庫的增改操作。

歡迎大家指正