コード例 #1
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("This program displays current weather in Saint Petersburg.");

            while (true)
            {
                MyHttpClient client = new MyHttpClient();

                IParser parserOpenWeather = new ParserOpenWeather(client);
                IParser parserTomorrowIo  = new ParserTomorrowIo(client);

                await GetWeather(parserOpenWeather);
                await GetWeather(parserTomorrowIo);

                ConsoleOutput.OutputExitMessage();

                if (Console.ReadLine() == "")
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
コード例 #2
0
        public static YoutubeVideo GetYoutubeVideo(string videoId)
        {
            var client = new MyHttpClient();
            var json   = JObject.Parse(client.Get(
                                           $"https://www.googleapis.com/youtube/v3/videos?id={videoId}&key={ApiKey}&part=liveStreamingDetails,snippet"));

            if (json["pageInfo"]["totalResults"].ToObject <int>() != 1)
            {
                return(null);
            }
            var item    = json["items"].First();
            var snippet = item["snippet"];
            var result  = new YoutubeVideo()
            {
                Title         = snippet["title"].ToObject <string>(),
                PublishTime   = DateTime.Parse(snippet["publishedAt"].ToObject <string>()),
                ChannelId     = snippet["channelId"].ToObject <string>(),
                VideoId       = item["id"].ToObject <string>(),
                VideoLink     = "https://www.youtube.com/watch?v=" + item["id"].ToObject <string>(),
                ChannelTitle  = snippet["channelTitle"].ToObject <string>(),
                ThumbnailLink = snippet["thumbnails"]["default"]["url"].ToObject <string>(),
                Description   = snippet["description"].ToObject <string>(),
                IsLive        = snippet["liveBroadcastContent"].ToObject <string>() == "live",
            };

            if (item["liveStreamingDetails"] != null)
            {
                result.LiveDetails = item["liveStreamingDetails"].ToObject <LiveStreamingDetail>();
            }
            return(result);
        }
コード例 #3
0
        public void GettingDataTest()
        {
            MyHttpClient myHttpClient = new MyHttpClient();
            var          response     = myHttpClient.GetData("https://api.openweathermap.org/data/2.5/weather?lon=2340.2642&lat=59.8944&units=metric&appid=");

            Assert.IsNotNull(response);
        }
コード例 #4
0
        private async void LoadWeather()
        {
            MyHttpClient client = new MyHttpClient();

            IParser parserTomorrowIo  = new ParserTomorrowIo(client);
            IParser parserOpenWeather = new ParserOpenWeather(client);

            Weather.Weather weatherTomorrowIo;
            Weather.Weather weatherOpenWeather;

            try
            {
                weatherTomorrowIo = await GetWeather(parserTomorrowIo);
            }
            catch
            {
                weatherTomorrowIo = null;
            }

            try
            {
                weatherOpenWeather = await GetWeather(parserOpenWeather);
            }
            catch
            {
                weatherOpenWeather = null;
            }

            UpdateGrid(tomorrowIoGrid, weatherTomorrowIo);

            UpdateGrid(openWeatherGrid, weatherOpenWeather);
        }
コード例 #5
0
        public static List <HiyokoStreamerInfo> SearchStreamer(string keyword)
        {
            var client      = new MyHttpClient();
            var requestJson = new JObject()
            {
                ["user_token"]    = null,
                ["keyword"]       = keyword,
                ["groups"]        = string.Empty,
                ["inc_old_group"] = 0,
                ["retired"]       = "all",
                ["following"]     = "all",
                ["notifications"] = "all"
            };
            var json = JObject.Parse(client.Post("https://hiyoko.sonoj.net/f/avtapi/search/streamer/fetch",
                                                 requestJson.ToString(Formatting.None), "application/json"));

            if (!json["result"].Any())
            {
                return(new List <HiyokoStreamerInfo>());
            }

            return(json["result"]
                   .Select(token => JObject.Parse(client.Post("https://hiyoko.sonoj.net/f/avtapi/strm/fetch_summary",
                                                              "{\"streamer_id\":\"" + token["streamer_id"].ToObject <string>() + "\"}", "application/json")))
                   .Select(infoJson => new HiyokoStreamerInfo
            {
                Channels = JsonConvert.DeserializeObject <HiyokoChannelInfo[]>(infoJson["channels"].ToString()),
                Name = infoJson["streamer"]["name"].ToObject <string>(),
                TwitterId = infoJson["streamer"]["twitter_id"].ToObject <string>()
            }).ToList());
        }
コード例 #6
0
        public static YoutubeLiveChatInfo GetLiveChatInfo(string liveChatId)
        {
            var client = new MyHttpClient();

            return(JsonConvert.DeserializeObject <YoutubeLiveChatInfo>(client.Get(
                                                                           $"https://www.googleapis.com/youtube/v3/liveChat/messages?liveChatId={liveChatId}&part=id%2Csnippet&key={ApiKey}&maxResults=2000")));
        }
コード例 #7
0
        //Max return 50 videos...
        public static List <YoutubeVideo> GetVideosByChannelId(string channelId, int count = 5)
        {
            var client = new MyHttpClient();
            var json   = JObject.Parse(client.Get(
                                           $"https://www.googleapis.com/youtube/v3/search?key={ApiKey}&channelId={channelId}&part=snippet,id&order=date&maxResults={count}"));
            var a = json.ToString();

            if (json["items"] == null)
            {
                return(new List <YoutubeVideo>());
            }
            var result = (from token in json["items"]
                          where token["id"]["kind"].ToObject <string>() == "youtube#video"
                          let snippet = token["snippet"]
                                        select new YoutubeVideo()
            {
                Title = snippet["title"].ToObject <string>(),
                PublishTime = DateTime.Parse(snippet["publishedAt"].ToObject <string>()),
                ChannelId = snippet["channelId"].ToObject <string>(),
                VideoId = token["id"]["videoId"].ToObject <string>(),
                VideoLink = "https://www.youtube.com/watch?v=" + token["id"]["videoId"].ToObject <string>(),
                ChannelTitle = snippet["channelTitle"].ToObject <string>(),
                ThumbnailLink = snippet["thumbnails"]["default"]["url"].ToObject <string>(),
                Description = snippet["description"].ToObject <string>(),
                IsLive = snippet["liveBroadcastContent"].ToObject <string>() == "live"
            }).ToList();

            return(result);
        }
コード例 #8
0
        public static BiliBiliUser GetBiliBiliUser(long userId)
        {
            var client = new MyHttpClient();
            var json   = JObject.Parse(client.Get($"https://api.bilibili.com/x/space/app/index?mid={userId}"));

            return(json["data"]["info"].ToObject <BiliBiliUser>());
        }
コード例 #9
0
 private void FormConfirm_Shown(object sender, EventArgs e)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             foreach (Product product in Products)
             {
                 HttpUtil.LoginToShopWebsite(product.Username, product.Password);
                 List <string> uploadPicturesResult = HttpUtil.UploadPictureToWebsite(product.Pictures);
                 product.PictureUrls = uploadPicturesResult;
                 MyHttpClient.Dispose();
             }
             this.btnUpload.Text    = "确认无误并且上传";
             this.btnUpload.Enabled = true;
             btnUploadProduct_Click(null, null);
             this.Hide();
         }
         catch (Exception exception)
         {
             FileLog.Error("FormConfirm_Shown", exception, LogType.Error);
             MessageBox.Show(exception.Message);
             MessageBox.Show("上传图片时出现问题,请查看网络连接情况!如还有其他问题,联系开发者.");
         }
     });
 }
コード例 #10
0
        private async void LoadWeather()
        {
            MyHttpClient client = new MyHttpClient();

            IParser parserTomorrowIo  = new ParserTomorrowIo(client);
            IParser parserOpenWeather = new ParserOpenWeather(client);

            _weatherTomorrowIo = await GetWeather(parserTomorrowIo);

            _weatherOpenWeather = await GetWeather(parserOpenWeather);

            try
            {
                _weatherTomorrowIo = await GetWeather(parserTomorrowIo);
            }
            catch
            {
                _weatherTomorrowIo = null;
            }

            try
            {
                _weatherOpenWeather = await GetWeather(parserOpenWeather);
            }
            catch
            {
                _weatherOpenWeather = null;
            }

            UpdatePanelData(rightPanel, _weatherTomorrowIo);

            UpdatePanelData(leftPanel, _weatherOpenWeather);
        }
コード例 #11
0
    public HttpResponseMessage DoWork()
    {
        MyHttpClient myClient = new MyHttpClient();
        var          task     = myClient.RunAsyncGet();

        return(task.Result);
    }
コード例 #12
0
ファイル: User.cs プロジェクト: OpportunityLiu/Bangumi-UWP
 public static IAsyncOperationWithProgress <User, HttpProgress> FetchAsync(string userName)
 {
     if (string.IsNullOrWhiteSpace(userName))
     {
         throw new ArgumentException("用户名或 UID 不能为空");
     }
     return(MyHttpClient.GetJsonAsync <User>(new Uri(Config.ApiUri, $"/user/{userName.Trim()}")));
 }
コード例 #13
0
        public SignInPage()
        {
            InitializeComponent();

            httpClient   = new HttpClient();
            myHttpClient = new MyHttpClient();

            BindingContext = _authenticationViewModel = new AuthenticationViewModel();
        }
コード例 #14
0
        public void GetActualAPICall()
        {
            IHttpClient         client = new MyHttpClient();
            MetaWeatherForecast sut    = new MetaWeatherForecast(client);
            Forecast            forecast;

            forecast = sut.GetWeatherForecast("prague");
            Assert.False(string.IsNullOrEmpty(forecast.Condition));
        }
コード例 #15
0
        public static string GetUploadsPlaylistId(string channelId)
        {
            var client = new MyHttpClient();
            var json   = JObject.Parse(client.Get(
                                           $"https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={channelId}&key={ApiKey}"));

            return(json["pageInfo"]["totalResults"].ToObject <int>() == 0
                ? null
                : json["items"].First()["contentDetails"]["relatedPlaylists"]["uploads"].ToObject <string>());
        }
コード例 #16
0
        public static string GetLiveVideoId(string channelId)
        {
            var html = new MyHttpClient().Get($"https://www.youtube.com/channel/{channelId}/featured", string.Empty);
            var doc  = new HtmlDocument();

            doc.LoadHtml(html);
            var node = doc.DocumentNode.SelectSingleNode(
                "//*[@id=\"browse-items-primary\"]/li[1]/div/div/div/ul/li/div[1]/div[2]/h3/a");

            return(node?.Attributes.FirstOrDefault(v => v.Name == "href")?.Value.Split('=').Last());
        }
コード例 #17
0
        public static string GetFirstVideoId(string channelId)
        {
            var html = new MyHttpClient().Get($"https://www.youtube.com/channel/{channelId}/videos?pbj=1", string.Empty);
            var doc  = new HtmlDocument();

            doc.LoadHtml(html);
            var node = doc.DocumentNode.SelectSingleNode(
                "//*[@id=\"channels-browse-content-grid\"]/li[1]/div/div[1]/div[2]/h3/a");

            return(node.Attributes.FirstOrDefault(v => v.Name == "href")?.Value.Split('=').Last());
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: Phenon1/YandexAPI_Test_App
 protected static JsonUploadHref GetJsonFromURL(string qery)
 {
     using (MyHttpClient httpClient = new MyHttpClient())
     {
         var response = httpClient.GetAsync(qery + @"&overwrite=?true").Result;
         using (System.IO.StreamReader sr = new System.IO.StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.Default))
         {
             return(JsonConvert.DeserializeObject <JsonUploadHref>(sr.ReadToEnd()));
         }
     }
 }
コード例 #19
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dicData"></param>
        /// <returns></returns>
        private string MyLogin(Dictionary <string, Dictionary <string, string> > dicData)
        {
            Dictionary <string, string> dic     = dicData["sub"];
            Dictionary <string, string> dic_obj = dicData["obj"];
            var          userName = GetDicKeyValue(dic, "userName") ?? string.Empty;
            var          userPass = GetDicKeyValue(dic, "userPass") ?? string.Empty;
            var          type     = GetDicKeyValue(dic_obj, "type") ?? string.Empty;
            MyHttpClient client   = new MyHttpClient();

            return("");
        }
コード例 #20
0
ファイル: LiveClient.cs プロジェクト: shitianshiwa/VtuberBot
        public void InitDanmuServer()
        {
            var client = new MyHttpClient();
            var xml    = client.Get("https://live.bilibili.com/api/player?id=cid:" + RoomId);

            xml = $"<root>{xml}</root>";
            var doc = new XmlDocument();

            doc.LoadXml(xml);
            DanmuServer = doc["root"]["dm_host_list"].InnerText.Split(',').First();
        }
コード例 #21
0
        private static string CallClient(String urlManager, String key, string json)
        {
            //对报文做MD5处理  HttpUtility.UrlEncode(
            string data       = Convert.ToBase64String(Encoding.UTF8.GetBytes(UrlEncode(json, Encoding.UTF8)));
            string keyContent = Get16MD5(data + key);
            String URL        = urlManager + "&data=" + data + "&md5_data=" + keyContent + "";

            MyHttpClient myWebClient = new MyHttpClient(URL);
            var          ret         = myWebClient.UploadString("", Encoding.UTF8);

            return(ret);
        }
コード例 #22
0
        private string GetZhaoPinDetailsInfo(Dictionary <string, string> dic, HttpContext context)
        {
            MyHttpClient client = new MyHttpClient();

            try
            {
                return(client.GetUrlInfo(context.Server.UrlDecode(dic["url"]), dic["type"]));
            }
            catch (Exception ex)
            {
                return(("后台请求异常~请联系管理员[email protected]" + ex.ToString()).ToJson());
            }
        }
コード例 #23
0
        public static List <HiyokoTimelineItem> GetLiveTimeline(string date)
        {
            var client      = new MyHttpClient();
            var requestJson = new JObject()
            {
                ["date"]       = date,
                ["user_token"] = null
            };

            return(JsonConvert.DeserializeObject <List <HiyokoTimelineItem> >(
                       JObject.Parse(client.Post("https://hiyoko.sonoj.net/f/avtapi/schedule/fetch_curr",
                                                 requestJson.ToString(Formatting.None), "application/json"))["schedules"].ToString()));
        }
コード例 #24
0
ファイル: TwitterApi.cs プロジェクト: shitianshiwa/VtuberBot
        public static void InitAccessToken()
        {
            var client = new MyHttpClient()
            {
                AccessToken = "Basic " + Config.DefaultConfig.TwitterApiKey
            };
            var json = JObject.Parse(client.Post("https://api.twitter.com/oauth2/token",
                                                 new Dictionary <string, string>()
            {
                ["grant_type"] = "client_credentials"
            }));

            AccessToken = json["access_token"].ToObject <string>();
        }
コード例 #25
0
ファイル: TwitterApi.cs プロジェクト: shitianshiwa/VtuberBot
        public static List <TweetInfo> GetTimelineByUser(string username, int count = 5)
        {
            if (string.IsNullOrEmpty(AccessToken))
            {
                InitAccessToken();
            }
            var client = new MyHttpClient()
            {
                AccessToken = "Bearer " + AccessToken
            };

            return(JsonConvert.DeserializeObject <List <TweetInfo> >(client.Get(
                                                                         $"https://api.twitter.com/1.1/statuses/user_timeline.json?count={count}&screen_name={username}")));
        }
コード例 #26
0
        /// <summary>
        /// 读取招聘详细信息
        /// </summary>
        /// <param name="dicData"></param>
        /// <returns></returns>
        private string GetZhaoPinInfo(Dictionary <string, Dictionary <string, string> > dicData)
        {
            Dictionary <string, string> dic     = dicData["sub"];
            Dictionary <string, string> dic_obj = dicData["obj"];
            var key           = GetDicKeyValue(dic, "inp_key") ?? ".net";
            var city          = GetDicKeyValue(dic, "sel_city") ?? "上海";
            var chk_zhilian   = GetDicKeyValue(dic, "chk_zhilian") ?? "False";
            var chk_liepin    = GetDicKeyValue(dic, "chk_liepin") ?? "False";
            var chk_qiancheng = GetDicKeyValue(dic, "chk_qiancheng") ?? "False";
            var chk_lashou    = GetDicKeyValue(dic, "chk_lashou") ?? "False";
            var index         = GetDicKeyValue(dic_obj, "index") ?? "1";

            var city_liepin    = DataClass.GetDic_liepin(city);
            var city_qiancheng = DataClass.GetDic_qiancheng(city);
            var city_zhilian   = DataClass.GetDic_zhilian(city);

            string url_智联招聘 = string.Format("http://sou.zhaopin.com/jobs/searchresult.ashx?jl={0}&kw={1}&p={2}", city_zhilian, key, index);
            string url_猎聘网  = string.Format("http://www.liepin.com/zhaopin/?key={0}&dqs={1}&curPage={2}", key, city_liepin, index);
            string url_前程无忧 = string.Format("http://search.51job.com/jobsearch/search_result.php?jobarea={0}&keyword={1}&curr_page={2}&fromJs=1", city_qiancheng, key, index);
            //            string url_拉勾网 = string.Format("http://www.lagou.com/jobs/list_{0}?city={1}&pn={2}", key, city_zhilian, index);//city_zhilian  这里和智联一样直接用的中文地址码
            string url_拉勾网 = string.Format("http://www.lagou.com/jobs/positionAjax.json?city={0}", city_zhilian);

            List <ZhaopinInfo> zpInfoList = new List <ZhaopinInfo>();
            MyHttpClient       client     = new MyHttpClient();

            try
            {
                if (chk_zhilian == "True")
                {
                    client.GetRequest(ref zpInfoList, url_智联招聘, ZhaopinType.智联招聘);
                }
                if (chk_liepin == "True")
                {
                    client.GetRequest(ref zpInfoList, url_猎聘网, ZhaopinType.猎聘网);
                }
                if (chk_qiancheng == "True")
                {
                    client.GetRequest(ref zpInfoList, url_前程无忧, ZhaopinType.前程无忧);
                }
                if (chk_lashou == "True")
                {
                    client.GetRequest(ref zpInfoList, url_拉勾网, ZhaopinType.拉勾网, index, key);
                }
            }
            catch (Exception)
            { }

            return(zpInfoList.ToJson());
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: Phenon1/YandexAPI_Test_App
        static string uploadFile(string currentFile)
        {
            string fileName   = Path.GetFileName(currentFile);
            var    uploadHref = GetJsonFromURL(GetUrlUpload + "?" + pathOut + fileName);

            using (Stream stream = new StreamReader(currentFile).BaseStream)
            {
                using (MyHttpClient httpClient = new MyHttpClient())
                {
                    var response = httpClient.PutAsync(uploadHref.href, new StreamContent(stream)).Result;
                }
            }

            return(pathOut + fileName);
        }
コード例 #28
0
        public static List <UserLocalLiveInfo> GetTimeLine()
        {
            var client = new MyHttpClient();
            var text   = client.Get("http://virtual-youtuber.userlocal.jp/");
            var html   = new HtmlDocument();

            html.LoadHtml(text);
            var body     = html.DocumentNode.SelectNodes("html").First().SelectNodes("body").First();
            var listNode = body.SelectSingleNode("/html/body/div[2]/div[2]/div[3]/table").ChildNodes.Where(v => v.Name == "tr");
            var time     = string.Empty;
            var result   = new List <UserLocalLiveInfo>();

            foreach (var node in listNode)
            {
                if (node.GetAttributeValue("class") == "text-white bg-dark")
                {
                    time = node.InnerText.Trim();
                    time = time.Substring(0, time.IndexOf('('));
                    continue;
                }

                var subTime  = time;
                var subNodes = node.ChildNodes.Where(v => v.Name == "td");
                subTime += subNodes.First().InnerText.Trim();
                subNodes = subNodes.Last().ChildNodes.Where(v => v.Name == "div");
                foreach (var subNode in subNodes)
                {
                    var dateTime = Convert.ToDateTime(subTime + subNode.ChildNodes.First(v => v.Name == "div").InnerText.Trim(), new DateTimeFormatInfo()
                    {
                        ShortDatePattern = "MM月dd日hh時mm分"
                    });
                    dateTime += new TimeSpan(1, 0, 0);
                    var spans = subNode.ChildNodes.Last(v => v.Name == "div").ChildNodes.Where(v => v.Name == "span");
                    result.AddRange(from span in spans
                                    select span.InnerText.Trim()
                                    into titleOrigin
                                    let liveTitle = titleOrigin.Substring(0, titleOrigin.IndexOf("(") == -1 ? titleOrigin.Length : titleOrigin.IndexOf("(")).Trim()
                                                    let vtuberName =
                                        titleOrigin.Substring(titleOrigin.IndexOf("(") + 1,
                                                              titleOrigin.Length - titleOrigin.IndexOf("(") - 2)
                                        select new UserLocalLiveInfo()
                    {
                        LiveTime = dateTime, Title = liveTitle, VTuber = vtuberName
                    });
                }
            }
            return(result);
        }
コード例 #29
0
ファイル: Client.cs プロジェクト: steamb23/E-Viewer
        private Client()
        {
            var httpFilter = new HttpBaseProtocolFilter {
                AllowAutoRedirect = false
            };

            httpFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
            CookieManager = httpFilter.CookieManager;
            HttpClient    = new MyHttpClient(this, new HttpClient(new RedirectFilter(httpFilter)));
            _SetDefaultCookies();

            if (NeedLogOn)
            {
                ClearLogOnInfo();
            }
        }
コード例 #30
0
        public void Init_accessToken()
        {
            MyHttpClient a = MyHttpClient.getInstance(path_dir + "outgoing.CertwithKey.pkcs12", "IoM@1234", path_dir + "ca.jks", "Huawei@123");

            Map paramLogin = new HashMap();

            paramLogin.put("appId", appId);
            paramLogin.put("secret", secret);

            ResponseMsg b = a.sendMsg(url_login, paramLogin);
            HttpsUtil   http_utils_test = new HttpsUtil();

            string login_str = b.getContent().ToString();

            System.Diagnostics.Debug.WriteLine(login_str);
            accessToken_str = extract_data_from_json(login_str, "\"accessToken\"", 0).Replace("\"", "");//删除双引号,这里获取的accessToken以后会用到
            System.Diagnostics.Debug.WriteLine(accessToken_str);
        }