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

C# HttpClient类代码示例

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

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



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

示例1: GetRequest

        private static async Task<string> GetRequest(string uri)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(new Uri(uri));
                    if (!response.IsSuccessStatusCode)
                    {
                        if (response.StatusCode == HttpStatusCode.InternalServerError)
                        {
                            throw new Exception(HttpStatusCode.InternalServerError.ToString());
                        }
                        else
                        {
                            // Throw default exception for other errors
                            response.EnsureSuccessStatusCode();
                        }
                    }

                    return await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    // An unhandled exception has occurred; break into the debugger
                    System.Diagnostics.Debugger.Break();
                }

                throw;
            }
        }
开发者ID:birkancilingir,项目名称:tdk-dictionary-win10,代码行数:34,代码来源:DictionaryDataService.cs


示例2: SendRequest

        public async Task<bool> SendRequest()
        {
            try
            {
                var config = new ConfigurationViewModel();
                var uri = new Uri(config.Uri + _path);

                var filter = new HttpBaseProtocolFilter();
                if (config.IsSelfSigned == true)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                }

                var httpClient = new HttpClient(filter);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain"));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString()));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString()));

                var reponse = await httpClient.GetAsync(uri);
                httpClient.Dispose();
                return reponse.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:phabrys,项目名称:Domojee,代码行数:29,代码来源:HttpRpcClient.cs


示例3: SearchForPlayers

        public SearchForPlayers(HttpClient Client, StatsDatabase Driver)
        {
            string Nick;
            List<Dictionary<string, object>> Rows;

            // Setup Params
            if (!Client.Request.QueryString.ContainsKey("nick"))
            {
                Client.Response.WriteResponseStart(false);
                Client.Response.WriteHeaderLine("asof", "err");
                Client.Response.WriteDataLine(DateTime.UtcNow.ToUnixTimestamp(), "Invalid Syntax!");
                Client.Response.Send();
                return;
            }
            else
                Nick = Client.Request.QueryString["nick"];

            // Timestamp Header
            Client.Response.WriteResponseStart();
            Client.Response.WriteHeaderLine("asof");
            Client.Response.WriteDataLine(DateTime.UtcNow.ToUnixTimestamp());

            // Output status
            int i = 0;
            Client.Response.WriteHeaderLine("n", "pid", "nick", "score");
            Rows = Driver.Query("SELECT id, name, score FROM player WHERE name LIKE @P0 LIMIT 20", "%" + Nick + "%");
            foreach (Dictionary<string, object> Player in Rows)
            {
                Client.Response.WriteDataLine(i + 1, Rows[i]["id"], Rows[i]["name"].ToString().Trim(), Rows[i]["score"]);
                i++;
            }

            // Send Response
            Client.Response.Send();
        }
开发者ID:roguesupport,项目名称:ControlCenter,代码行数:35,代码来源:SearchForPlayers.cs


示例4: Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException

 public async Task Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
 {
     using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic }))
     {
         await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
     }
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:HttpClientHandlerTest.ClientCertificates.cs


示例5: Can_define_custom_parameter_binder

 public async Task Can_define_custom_parameter_binder()
 {
     var client = new HttpClient();
     var res = await client.GetAsync("http://localhost:8080/whatipami");
     var cont = await res.Content.ReadAsStringAsync();
     Assert.Equal("::1", cont);
 }
开发者ID:pmhsfelix,项目名称:ndc-london-13-web-api,代码行数:7,代码来源:ParameterBindingFacts.cs


示例6: HttpPost

        public static async void HttpPost(string id,string phone,string image, string name, string content, string time,string atName,string atPhone,string atImage)
        {
            try
            {

                HttpClient httpClient = new HttpClient();
                string posturi = Config.apiCommentPublish;
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi));
                HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent(
                    new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string,string>("id",id),
                        new KeyValuePair<string,string>("phone",phone),
                        new KeyValuePair<string, string>("image", image),
                        new KeyValuePair<string, string>("name", name),
                        new KeyValuePair<string, string>("content", content),
                        new KeyValuePair<string, string>("time", time),
                        new KeyValuePair<string, string>("atName", atName),
                        new KeyValuePair<string, string>("atPhone", atPhone),
                        new KeyValuePair<string, string>("atImage", atImage),
                    }
                );
                request.Content = postData;
                HttpResponseMessage response = await httpClient.SendRequestAsync(request);
              }
            catch (Exception ex)
            {
                HelpMethods.Msg(ex.Message.ToString());
            }
        }
开发者ID:x01673,项目名称:dreaming,代码行数:30,代码来源:HttpPostComment.cs


示例7: Main

    static void Main(string[] args)
    {
        Uri baseAddress = new Uri("http://ncs-sz-jinnan:3721");
        HttpClient httpClient = new HttpClient { BaseAddress = baseAddress };
        IEnumerable<Contact> contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        Console.WriteLine("当前联系人列表");
        ListContacts(contacts);

        Contact contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "789" };
        Console.WriteLine("\n添加联系人003");
        httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;            
        ListContacts(contacts);

        contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "987" };
        Console.WriteLine("\n修改联系人003");
        httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        ListContacts(contacts);

        Console.WriteLine("\n删除联系人003");
        httpClient.DeleteAsync("/api/contacts/003").Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        ListContacts(contacts);

            
        Console.Read();
    }
开发者ID:xiaohong2015,项目名称:.NET,代码行数:28,代码来源:Program.cs


示例8: DownloadAsync

        internal static async Task<InternetRequestResult> DownloadAsync(InternetRequestSettings settings)
        {
            InternetRequestResult result = new InternetRequestResult();
            try
            {
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");

                if (!string.IsNullOrEmpty(settings.UserAgent))
                {
                    httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent);
                }

                HttpResponseMessage response = await httpClient.GetAsync(settings.RequestedUri);
                result.StatusCode = response.StatusCode;
                if (response.IsSuccessStatusCode)
                {
                    FixInvalidCharset(response);
                    result.Result = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception)
            {
                result.StatusCode = HttpStatusCode.InternalServerError;
                result.Result = string.Empty;
            }
            return result;
        }
开发者ID:glebanych,项目名称:hromadske-windows,代码行数:28,代码来源:InternetRequest.cs


示例9: HttpClient_ClientUsesAuxRecord_Ok

        public async Task HttpClient_ClientUsesAuxRecord_Ok()
        {
            X509Certificate2 serverCert = Configuration.Certificates.GetServerCertificate();

            var server = new SchSendAuxRecordTestServer(serverCert);
            int port = server.StartServer();

            string requestString = "https://localhost:" + port.ToString();
            
            using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
            using (var client = new HttpClient(handler))
            {
                var tasks = new Task[2];
                tasks[0] = server.RunTest();
                tasks[1] = client.GetStringAsync(requestString);
            
                await Task.WhenAll(tasks).TimeoutAfter(15 * 1000);
            
                if (server.IsInconclusive)
                {
                    _output.WriteLine("Test inconclusive: The Operating system preferred a non-CBC or Null cipher.");
                }
                else
                {
                    Assert.True(server.AuxRecordDetected, "Server reports: Client auxiliary record not detected.");
                }
            }
        }
开发者ID:Corillian,项目名称:corefx,代码行数:28,代码来源:SchSendAuxRecordHttpTest.cs


示例10: LightColorTask

        private static async Task<string> LightColorTask(int hue, int sat, int bri, int Id)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();
                HttpStringContent content
                    = new HttpStringContent
                          ($"{{ \"bri\": {bri} , \"hue\": {hue} , \"sat\": {sat}}}",
                            Windows.Storage.Streams.UnicodeEncoding.Utf8,
                            "application/json");
                //MainPage.RetrieveSettings(out ip, out port, out username);

                Uri uriLampState = new Uri($"http://{ip}:{port}/api/{username}/lights/{Id}/state");
                var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

                string jsonResponse = await response.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return string.Empty;
            }
        }
开发者ID:Jeroentjuh99,项目名称:equanimous-octo-quack,代码行数:35,代码来源:SendAndReceive.cs


示例11: PostStringAsync

        public async Task<string> PostStringAsync(string link, string param)
        {

            try
            {

                System.Diagnostics.Debug.WriteLine(param);

                Uri uri = new Uri(link);

                HttpClient httpClient = new HttpClient();


                HttpStringContent httpStringContent = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/x-www-form-urlencoded"); //,Windows.Storage.Streams.UnicodeEncoding.Utf8
                
                HttpResponseMessage response = await httpClient.PostAsync(uri,

                                                       httpStringContent).AsTask(cts.Token);
                responseHeaders = response.Headers;
                System.Diagnostics.Debug.WriteLine(responseHeaders);

                string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);
                return responseBody;
            }
            catch(Exception e)
            {
                return "Error:" + e.Message;
            }

        }
开发者ID:xulihang,项目名称:jnrain-wp,代码行数:30,代码来源:httputils.cs


示例12: GetNotifications

        public async Task<List<Notification>> GetNotifications()
        {
            HttpResponseMessage response = null;
            HttpRequestMessage request = null;

            using (var httpClient = new HttpClient())
            {
                request = new HttpRequestMessage(HttpMethod.Get, new Uri(Const.UrlNotifyWithTimeStamp));
                response = await httpClient.SendRequestAsync(request);
            }

            var respList = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());

            List<Notification> notList = new List<Notification>();

            if (respList.HasValues)
            {
                var c = respList.First.First;

                for (int i = 0; i < c.Count(); i++)
                {
                    var ele = (JProperty)c.ElementAt(i);
                    Notification n = JsonConvert.DeserializeObject<Notification>(ele.Value.ToString());

                    n.AddedDate = new DateTime(1970, 1, 1).AddMilliseconds((long)(((JValue)ele.Value["Data"]).Value));
                    n.PublicationId = ele.Name.Split(':')[0];
                    n.Id = ele.Name.Split(':')[1];
                    n.TypeValue = Enum.ParseToNotificationType(((JValue)ele.Value["Type"]).Value.ToString());
                    notList.Add(n);
                }
            }
            notList = notList.OrderBy(n => n.Status).ThenByDescending(n => n.AddedDate).ToList();

            return notList;
        }
开发者ID:djfoxer,项目名称:dp.notification,代码行数:35,代码来源:DpLogic.cs


示例13: SetSessionCookie

        public async Task<Tuple<bool, DateTime?>> SetSessionCookie(string login, string password)
        {
            HttpResponseMessage response = null;
            HttpRequestMessage request = null;

            using (var httpClient = new HttpClient())
            {
                request = new HttpRequestMessage(HttpMethod.Post, new Uri(Const.UrlLogin));
                request.Content = new HttpFormUrlEncodedContent(new[] {
                    new KeyValuePair<string, string>("what", "login"),
                    new KeyValuePair<string, string>("login", login),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("persistent", "true"),
                });

                try
                {
                    response = await httpClient.SendRequestAsync(request);
                }
                catch (Exception)
                {
                    return new Tuple<bool, DateTime?>(false, null);
                }
            }

            var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            var expireDate = httpFilter.CookieManager.GetCookies(new Uri(Const.UrlFullAddress)).First().Expires ?? DateTime.Now;

            return new Tuple<bool, DateTime?>(response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok, expireDate.DateTime);
        }
开发者ID:djfoxer,项目名称:dp.notification,代码行数:30,代码来源:DpLogic.cs


示例14: EnsureConnectWifi

        public static void EnsureConnectWifi(string ssidNameSubStr, string id = null, string pw = null)
        {
            Task.Run(async() => 
            {
                while (true)
                {
                    try
                    {
                        using (var client = new HttpClient())
                        {
                            var strGoogle = await client.GetStringAsync(new Uri("http://google.com"));
                        }

                        await Task.Delay(3000);
                    }
                    catch (Exception ex)
                    {
                        Log.e($"EX-NETWORK : {ex}");

                        try
                        {
                            await ConnectWifiAsync(ssidNameSubStr, id, pw);
                        }
                        catch (Exception ex2)
                        {
                            Log.e($"EX-WIFI : {ex2}");
                        }
                    }
                }
            });
        }
开发者ID:HyundongHwang,项目名称:HUwpBaseLib,代码行数:31,代码来源:HublUtils.cs


示例15: OnNavigatedTo

 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter();
     meteredConnectionFilter = new HttpMeteredConnectionFilter(baseProtocolFilter);
     httpClient = new HttpClient(meteredConnectionFilter);
     cts = new CancellationTokenSource();
 }
开发者ID:t-angma,项目名称:Windows-universal-samples,代码行数:7,代码来源:scenario12_meteredconnectionfilter.xaml.cs


示例16: ExecuteAsync

 public async Task<string> ExecuteAsync()
 {
     if (OAuthSettings.AccessToken != null)
     {
         return OAuthSettings.AccessToken;
     }
     else if (OAuthSettings.RefreshToken == null)
     {
         return null;
     }
     using (var client = new HttpClient())
     {
         var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{
                         {"grant_type","refresh_token"},
                         {"refresh_token", OAuthSettings.RefreshToken},
                         {"client_id", OAuthSettings.ClientId},
                         {"client_secret", OAuthSettings.ClientSecret}
                     });
         var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content);
         response.EnsureSuccessStatusCode();
         var contentString = await response.Content.ReadAsStringAsync();
         var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString);
         OAuthSettings.AccessToken = accessTokenInfo.AccessToken;
         OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken;
         return OAuthSettings.AccessToken;
     }
 }
开发者ID:jcorioland,项目名称:techdays-paris-2014-mvc-webapi,代码行数:27,代码来源:LoginPassivelyQuery.cs


示例17: receive_file

        public override async void receive_file(String devicename, String add, int not)
        {
            try
            {
                _httpurl = new Uri(add);
                _httpprogress = new Progress<HttpProgress>(ProgressHandler);

                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
                                
                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

                _httpclient = new HttpClient(filter);

                _cancel_token_source = new CancellationTokenSource();
                _cancel_token = _cancel_token_source.Token;

                scan_network_speed();
                _stopwatch.Start();

                _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);
                _datawriter = new DataWriter(filewriter);

                _timer.Cancel();

                _transferspeed /= 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();

                _buffer = await _httpresponse.Content.ReadAsBufferAsync();

                _datawriter.WriteBuffer(_buffer);
                await _datawriter.StoreAsync();

                _datawriter.Dispose();
                filewriter.Dispose();
                filestream.Dispose();

                _httpresponse.Content.Dispose();
                _httpresponse.Dispose();
                _httpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }            
        }
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:60,代码来源:Gsm_agent.cs


示例18: GPSOAuthClient

 public GPSOAuthClient(string email, string password)
 {
     this.email = email;
     this.password = password;
     client = new HttpClient();
     androidKey = GoogleKeyUtils.KeyFromB64(b64Key);
 }
开发者ID:kbettadapur,项目名称:MusicPlayer,代码行数:7,代码来源:GPSOAuthClient.cs


示例19: CallApi

        static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);

            Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result);
        }
开发者ID:okusnadi,项目名称:oauth2-simple,代码行数:7,代码来源:Program.cs


示例20: GetRepositoriesAsync

        public async Task<GithubQueryResult<Repository>> GetRepositoriesAsync(string query, int pageIndex = 1)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            if (query.IsBlank())
            {
                throw new ArgumentException("Github query could not be empty.", nameof(query));
            }

            if (pageIndex <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageIndex));
            }

            string queryEncoded = WebUtility.UrlEncode(query);
            string url = string.Format("https://api.github.com/search/repositories?q={0}&page={1}&per_page={2}&order=desc", queryEncoded, pageIndex, PAGE_SIZE);

            string json;
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.TryAppendWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240");
                json = await client.GetStringAsync(new Uri(url));
            }
            return JsonConvert.DeserializeObject<GithubQueryResult<Repository>>(json);
        }
开发者ID:Rasetech,项目名称:Template10,代码行数:28,代码来源:GithubService4RunTime.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# HttpClientHandler类代码示例发布时间:2022-05-24
下一篇:
C# HttpBaseProtocolFilter类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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