哈喽,筒子们。又是令人开心的周六
忙碌(搬砖)的一周又过去了,让我们来看一下今天要写点什么吧
首先接口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(""); }
抛砖引玉,我这里只是贴了一个简单的方法去获取到数据,并且进行了数据库的增改操作。
欢迎大家指正