• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Net.WebClient类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Net.WebClient的典型用法代码示例。如果您正苦于以下问题:C# WebClient类的具体用法?C# WebClient怎么用?C# WebClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



WebClient类属于System.Net命名空间,在下文中一共展示了WebClient类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: FindBooksByOLIDs

        public List<BookData> FindBooksByOLIDs(List<string> oLIDs)
        {
            if (oLIDs == null)
            {
                throw new ArgumentNullException("oLIDs");
            }

            List<BookData> books = new List<BookData>();

            var bibkeys = new StringBuilder();
            foreach (var oLID in oLIDs)
            {
                bibkeys.Append(oLID);
                bibkeys.Append(",");
            }
            if (bibkeys.Length != 0)
            {
                var getUri = baseUrl + "books?bibkeys=OLID:" + bibkeys.ToString().TrimEnd(new char[] { ',' }) + "&format=json&jscmd=data";

                using (var webClient = new WebClient())
                {
                    var response = JsonConvert.DeserializeObject<Dictionary<string, BookData>>(webClient.DownloadString(getUri));
                    if (response.Count() > 0)
                    {
                        books = new List<BookData>();
                        foreach (var value in response.Values)
                        {
                            books.Add(value);
                        }
                    }
                }
            }
            return books;
        }
开发者ID:zyq524,项目名称:Readgress,代码行数:34,代码来源:Details.cs


示例2: LoadXml

        /// <summary>
        /// loads a xml from the web server
        /// </summary>
        /// <param name="_url">URL of the XML file</param>
        /// <returns>A XmlDocument object of the XML file</returns>
        public static XmlDocument LoadXml(string _url)
        {
            var xmlDoc = new XmlDocument();
            
            try
            {
                while (Helper.pingForum("forum.mods.de", 10000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                xmlDoc.Load(_url);
            }
            catch (XmlException)
            {
                while (Helper.pingForum("forum.mods.de", 100000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                WebClient client = new WebClient(); ;
                Stream stream = client.OpenRead(_url);
                StreamReader reader = new StreamReader(stream);
                string content = reader.ReadToEnd();

                content = RemoveTroublesomeCharacters(content);
                xmlDoc.LoadXml(content);
            }

            return xmlDoc;
        }
开发者ID:tpf89,项目名称:mods.de-XML-Parser-for-Windows,代码行数:38,代码来源:Helper.cs


示例3: GetVersion

        public async override Task<IEnumerable<string>> GetVersion(string packageName)
        {
            if (string.IsNullOrEmpty(packageName))
                return Enumerable.Empty<string>();

            string url = $"http://registry.npmjs.org/{packageName}";
            string json = "{}";

            using (var client = new WebClient())
            {
                json = await client.DownloadStringTaskAsync(url);
            }

            var array = JObject.Parse(json);
            var time = array["time"];

            if (time == null)
                return Enumerable.Empty<string>();

            var props = time.Children<JProperty>();

            return from version in props
                   where char.IsNumber(version.Name[0])
                   orderby version.Name descending
                   select version.Name;
        }
开发者ID:yannduran,项目名称:PackageInstaller,代码行数:26,代码来源:Npm.cs


示例4: Search

        public List<SearchResult> Search(string searchQuery)
        {
            string url = "http://www.imdb.com/find?q={0}&s=all".Fmt(searchQuery);

            string html = new WebClient().DownloadString(url);

            CQ dom = html;

            var searchResults = new List<SearchResult>();

            foreach (var fragment in dom.Select("table.findList tr.findResult"))
            {
                var searchResult = new SearchResult();
                searchResult.ImageUrl = fragment.Cq().Find(".primary_photo > a > img").Attr("src");
                searchResult.Text = fragment.Cq().Find(".result_text").Html();
                searchResult.Text = StringEx.RemoveHtmlTags(searchResult.Text);

                string filmUrl = fragment.Cq().Find(".result_text > a").Attr("href");
                filmUrl = filmUrl.Replace("/title/", "");
                searchResult.FilmId = filmUrl.Substring(0, filmUrl.IndexOf("/"));

                searchResults.Add(searchResult);
            }

            return searchResults;
        }
开发者ID:jivkopetiov,项目名称:ImdbForums,代码行数:26,代码来源:ImdbScraper.cs


示例5: ItemCrawler

 public ItemCrawler(Uri url)
 {
     _htmlDocument = new HtmlDocument();
     var html = new WebClient().DownloadString(url.OriginalString);
     _htmlDocument.LoadHtml(html);
     _document = _htmlDocument.DocumentNode;
 }
开发者ID:stiano,项目名称:ShopperDopper,代码行数:7,代码来源:ItemCrawler.cs


示例6: DownloadQueue

		public async Task<Queue> DownloadQueue()
		{
			using (WebClient w = new WebClient())
			{
				return this.ConvertApiResultToQueue(await w.DownloadStringTaskAsync("http://localhost:8080/sabnzbd/api?mode=queue&output=xml"));
			}
		}
开发者ID:CSharpFan,项目名称:SABnzbd.UI,代码行数:7,代码来源:Connector.cs


示例7: GetCoinInformation

        public static List<CoinInformation> GetCoinInformation(string userAgent = "",
            BaseCoin profitabilityBasis = BaseCoin.Bitcoin)
        {
            WebClient client = new WebClient();
            if (!string.IsNullOrEmpty(userAgent))
                client.Headers.Add("user-agent", userAgent);

            string apiUrl = GetApiUrl(profitabilityBasis);

            string jsonString = client.DownloadString(apiUrl);
            JArray jsonArray = JArray.Parse(jsonString);

            List<CoinInformation> result = new List<CoinInformation>();

            foreach (JToken jToken in jsonArray)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(jToken);
                if (coinInformation.Difficulty > 0)
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
            }

            return result;
        }
开发者ID:nwfella,项目名称:MultiMiner,代码行数:26,代码来源:ApiContext.cs


示例8: HttpClient

		public HttpClient (Uri baseUrl)
		{
//			this.baseUrl = baseUrl;
			visualizeUrl = new Uri (baseUrl, "visualize");
			stopVisualizingUrl = new Uri (baseUrl, "stopVisualizing");
			client = new WebClient ();
		}
开发者ID:Applied-Duality,项目名称:LiveCode,代码行数:7,代码来源:HttpClient.cs


示例9: TranslateString

        /// <summary>
        /// Used to perform the actual conversion of the input string
        /// </summary>
        /// <param name="InputString"></param>
        /// <returns></returns>
        public override string TranslateString(string InputString)
        {
            Console.WriteLine("Processing: " + InputString);
            string result = "";

            using (WebClient client = new WebClient())
            {
                using (Stream data = client.OpenRead(this.BuildRequestString(InputString)))
                {

                    using (StreamReader reader = new StreamReader(data))
                    {
                        string s = reader.ReadToEnd();

                        result = ExtractTranslatedString(s);

                        reader.Close();
                    }

                    data.Close();
                }
            }

            return result;
        }
开发者ID:chrislbennett,项目名称:AndroidTranslator,代码行数:30,代码来源:GoogleAPI.cs


示例10: UpdateFiles

        public void UpdateFiles()
        {
            try
            {
                WriteLine("Local version: " + Start.m_Version);

                WebClient wc = new WebClient();
                string versionstr;
                using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt")))
                {
                    versionstr = sr.ReadLine();
                }
                Version remoteversion = new Version(versionstr);
                WriteLine("Remote version: " + remoteversion);

                if(Start.m_Version < remoteversion)
                {
                    foreach(string str in m_Files)
                    {
                        WriteLine("Updating: " + str);
                        wc.DownloadFile(baseurl + str, str);
                    }
                }
                wc.Dispose();
                WriteLine("Update complete");
            }
            catch(Exception e)
            {
                WriteLine("Update failed:");
                WriteLine(e);
            }
            this.Button_Ok.Enabled = true;
        }
开发者ID:BackupTheBerlios,项目名称:nomp-svn,代码行数:33,代码来源:frmUpdate.cs


示例11: AddNewGameHistory

        public GamePlayHistory AddNewGameHistory(GamePlayHistory gamePlayHistory)
        {
            if (string.IsNullOrEmpty(ToSavourToken))
            {
                throw new InvalidOperationException("No ToSavour Token is set");
            }

            RequestClient = new WebClient();
            RequestClient.Headers.Add("Authorization", ToSavourToken);
            RequestClient.Headers.Add("Content-Type", "application/json");

            var memoryStream = new MemoryStream();
            GetSerializer(typeof(GamePlayHistory)).WriteObject(memoryStream, gamePlayHistory);

            memoryStream.Position = 0;
            var sr = new StreamReader(memoryStream);
            var json = sr.ReadToEnd();

            var userJsonString = RequestClient.UploadString(_host + @"gamehistories", json);

            var byteArray = Encoding.ASCII.GetBytes(userJsonString);
            var stream = new MemoryStream(byteArray);

            var returnedGamePlayHistory = GetSerializer(typeof(GamePlayHistory)).ReadObject(stream) as GamePlayHistory;

            return returnedGamePlayHistory;
        }
开发者ID:NBitionDevelopment,项目名称:ToSavour-Service,代码行数:27,代码来源:ServiceOracle.cs


示例12: CreateIncident

        private void CreateIncident()
        {
            WebClient client = new WebClient();
            client.Headers[HttpRequestHeader.Accept] = "application/json";
            client.Headers[HttpRequestHeader.ContentType] = "application/json";

            client.UploadStringCompleted += (object source, UploadStringCompletedEventArgs e) =>
            {
                if (e.Error != null || e.Cancelled)
                {
                    Console.WriteLine("Error" + e.Error);
                    Console.ReadKey();
                }
            };

            JavaScriptSerializer js = new JavaScriptSerializer();
            TriggerDetails triggerDetails = new TriggerDetails(Component, Details);
            var detailJson = js.Serialize(triggerDetails);

            //Alert name should be unique for each alert - as alert name is used as incident key in pagerduty.
            string key = ConfigurationManager.AppSettings["PagerDutyServiceKey"];
            if (!string.IsNullOrEmpty(EscPolicy))
            {
                key = ConfigurationManager.AppSettings["PagerDutySev1ServiceKey"];
            }
            if (string.IsNullOrEmpty(key))
            {
                key = ConfigurationManager.AppSettings["PagerDutyServiceKey"];
            }
            
            Trigger trigger = new Trigger(key,AlertName,AlertSubject,detailJson);           
            var triggerJson = js.Serialize(trigger);
            client.UploadString(new Uri("https://events.pagerduty.com/generic/2010-04-15/create_event.json"), triggerJson); 
            
        }
开发者ID:NuGet,项目名称:NuGet.Services.Dashboard,代码行数:35,代码来源:SendAlertMailTask.cs


示例13: UserAuthenticate

        protected void UserAuthenticate(object sender, AuthenticateEventArgs e)
        {
            if (Membership.ValidateUser(this.LoginForm.UserName, this.LoginForm.Password))
            {
                e.Authenticated = true;
                return;
            }

            string url = string.Format(
                this.ForumAuthUrl,
                HttpUtility.UrlEncode(this.LoginForm.UserName),
                HttpUtility.UrlEncode(this.LoginForm.Password)
                );

            WebClient web = new WebClient();
            string response = web.DownloadString(url);

            if (response.Contains(groupId))
            {
                e.Authenticated = Membership.ValidateUser("Premier Subscriber", "danu2HEt");
                this.LoginForm.UserName = "Premier Subscriber";

                HttpCookie cookie = new HttpCookie("ForumUsername", this.LoginForm.UserName);
                cookie.Expires = DateTime.Now.AddMonths(2);

                Response.Cookies.Add(cookie);
            }
        }
开发者ID:mrkurt,项目名称:mubble-old,代码行数:28,代码来源:Login.aspx.cs


示例14: FindOLIDsByTitle

        public List<string> FindOLIDsByTitle(string title)
        {
            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentNullException("title");
            }

            // OpenLibrary is friendly with the book title whose first character is captial. 
            title = title[0].ToString().ToUpper() + title.Substring(1);

            var uri = baseUrl + "things?query={\"type\":\"\\/type\\/edition\",\"title~\":\"" + title + "*\"}&prettyprint=true&text=true";

            List<string> oLIDs = new List<string>();
            using (var webClient = new WebClient())
            {
                var response = JsonConvert.DeserializeObject<Thing>(webClient.DownloadString(uri));
                if (response.Status.Equals("ok", StringComparison.OrdinalIgnoreCase))
                {
                    foreach (var oLID in response.Result)
                    {
                        string strToRemove = "/books/";
                        if (oLID.StartsWith(strToRemove))
                        {
                            oLIDs.Add(oLID.Replace(strToRemove, ""));
                        }
                    }
                }
            }
            return oLIDs;
        }
开发者ID:zyq524,项目名称:Readgress,代码行数:30,代码来源:Details.cs


示例15: DELETE

        public static string DELETE(string uri, IDictionary<string, string> args)
        {
            try {
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;

                client.Headers["Connection"] = "Keep-Alive";
                StringBuilder formattedParams = new StringBuilder();

                IDictionary<string, string> parameters = new Dictionary<string, string>();

                foreach (var arg in args)
                {
                    parameters.Add(arg.Key, arg.Value);
                    formattedParams.AppendFormat("{0}={{{1}}}", arg.Key, arg.Key);
                }

                //Formatted URI
                Uri baseUri = new Uri(uri);

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompletedDelete);

                client.UploadStringAsync(baseUri, "DELETE", string.Empty);
                allDone.Reset();
                allDone.WaitOne();

                return requestResult;
            }
            catch (WebException ex) {
                return ReadResponse(ex.Response.GetResponseStream());
            }
        }
开发者ID:Injac,项目名称:InstaSharp-for-Windows-Phone-,代码行数:33,代码来源:HttpClient.cs


示例16: GetFilmThreads

        public List<Thread> GetFilmThreads(string filmId, int? page = null)
        {
            string url = "http://www.imdb.com/title/{0}/board".Fmt(filmId);

            if (page.HasValue)
                url += "?p=" + page.Value;

            string html = new WebClient().DownloadString(url);
            CQ dom = html;
            var threadHtmlFragments = dom.Select("div.threads > div.thread");
            var threads = new List<Thread>();

            foreach (var fragment in threadHtmlFragments)
            {
                if (fragment["class"] == "thread header")
                    continue;

                var cq = fragment.Cq();

                var thread = new Thread();

                thread.Title = cq.Find(">.title a").Html();
                thread.Url = cq.Find(">.title a").Attr("href");
                thread.Id = thread.Url.Substring(thread.Url.LastIndexOf("/") + 1);
                thread.UserUrl = cq.Find(".author .user a.nickname").Attr("href");
                thread.UserImage = cq.Find(".author .user .avatar > img").Attr("src");
                thread.UserName = cq.Find(".author .user a.nickname").Html();
                thread.RepliesCount = int.Parse(cq.Find(".replies a").Html().Trim());
                thread.Timestamp = ParseDate(cq.Find(".timestamp > a > span").Attr("title"), hasSeconds: false);

                threads.Add(thread);
            }

            return threads;
        }
开发者ID:jivkopetiov,项目名称:ImdbForums,代码行数:35,代码来源:ImdbScraper.cs


示例17: YouTubeDownloader

        public YouTubeDownloader(string youTubeVideoUrl)
        {
            _internalDownloader = new WebClient();
            _youTubeVideoUrl = youTubeVideoUrl;

            RegisterDownloadEventHandlers();
        }
开发者ID:neel,项目名称:Pion,代码行数:7,代码来源:YouTubeDownloader.cs


示例18: SetupClient

 static WebClient SetupClient()
 {
     var webClient = new WebClient();
     webClient.Headers.Add("user-agent", DefaultUserAgent);
     webClient.DownloadProgressChanged += OnDownloadProgressChanged;
     return webClient;
 }
开发者ID:erikols,项目名称:nget,代码行数:7,代码来源:HttpFetchClient.cs


示例19: downloadBinaryFile_Action

        public string downloadBinaryFile_Action(string urlOfFileToFetch, string targetFileOrFolder)
        {
            if (urlOfFileToFetch.is_Null() || targetFileOrFolder.is_Null())
                return null;
            var targetFile = targetFileOrFolder;
            if (Directory.Exists(targetFileOrFolder))
                targetFile = targetFileOrFolder.pathCombine(urlOfFileToFetch.fileName());

            PublicDI.log.debug("Downloading Binary File {0}", urlOfFileToFetch);
            lock (this)
            {
                using (var webClient = new WebClient())
                {
                    try
                    {
                        byte[] pageData = webClient.DownloadData(urlOfFileToFetch);
                        O2Kernel_Files.WriteFileContent(targetFile, pageData);
                        PublicDI.log.debug("Downloaded File saved to: {0}", targetFile);

                        webClient.Dispose();

                        GC.Collect();       // because of WebClient().GetRequestStream prob
                        return targetFile;
                    }
                    catch (Exception ex)
                    {
                        PublicDI.log.ex(ex);
                    }
                }
            }
            GC.Collect();       // because of WebClient().GetRequestStream prob
            return null;
        }
开发者ID:njmube,项目名称:FluentSharp,代码行数:33,代码来源:O2Kernel_Web.cs


示例20: GetStationCollectionAsync

        public static void GetStationCollectionAsync(IQueryBuilder url, RealTimeDataDelegate callback)
        {
            try
            {
                if (url == null) throw new Exception("Cannot work with null-objects");
                if (String.IsNullOrEmpty(url.Url)) throw new Exception("Url cannot be empty");

                var client = new WebClient();

                client.DownloadStringCompleted += (s, e) =>
                {
                    if (e.Error != null) throw e.Error;
                    if (e.Result == null) return;

                    var collection = JsonHelper.Deserialize<
                        IList<Station>>(e.Result);

                    callback(new ObservableCollection<Station>(collection));
                };

                client.DownloadStringAsync(new Uri(url.Url));
            }
            catch (Exception)
            {
                throw;
            }
        }
开发者ID:henningms,项目名称:trafikantendotnet,代码行数:27,代码来源:Realtime.cs



注:本文中的System.Net.WebClient类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Net.WebConnectionData类代码示例发布时间:2022-05-26
下一篇:
C# Net.WebAsyncResult类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap