当前位置: 首页>>代码示例>>C#>>正文


C# HttpClient类代码示例

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


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


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