使用.NETCoreApp 1.1在HttpClient上进行示例应用程序

时间:2017-07-19 05:35:19

标签: c# .net-core

我想向某个网站(URL)发送Http请求并获得响应(基本上我需要使用GetAsync和PutAsync方法),我需要在VS2017中使用.NETCoreApp 1.1。

  • 获取和发布
  • 设置标题
  • 忽略TLS证书错误

有没有人有一个简单的例子如何实现这个目标?

我在API文档HttpClient Class中找到了此示例,但目前尚不清楚如何实现上述要点。

1 个答案:

答案 0 :(得分:1)

我花了几个小时查看源代码corefx并提出了这个简单的例子

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace CoreFxHttpClientHandlerTest
{
    public class Program
    {
        private static void Main(string[] args)
        {            
        }

        public static async Task<bool> Run()
        {
            var ignoreTls = true;

            using (var httpClientHandler = new HttpClientHandler())
            {
                if (ignoreTls)
                {
                    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
                }

                using (var client = new HttpClient(httpClientHandler))
                {
                    using (HttpResponseMessage response = await client.GetAsync("https://test.com/get"))
                    {
                        Console.WriteLine(response.StatusCode);
                        var responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseContent);
                    }

                    using (var httpContent = new StringContent("{ \"id\": \"4\" }", Encoding.UTF8, "application/json"))
                    {
                        var request = new HttpRequestMessage(HttpMethod.Post, "http://test.com/api/users")
                        {
                            Content = httpContent
                        };
                        httpContent.Headers.Add("Cookie", "a:e");

                        using (HttpResponseMessage response = await client.SendAsync(request))
                        {
                            Console.WriteLine(response.StatusCode);
                            var responseContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine(responseContent);
                        }
                    }
                }
            }

            return true;
        }
    }
}

请参阅github中的代码。