2017-07-19 48 views
1

我想向某個網站(URL)發送Http請求並獲得響應(基本上我需要使用GetAsync和PutAsync方法),並且需要使用.NETCoreApp 1.1在VS2017。使用.NETCoreApp 1.1在HttpClient上的示例應用程序

  • 不要GET和POST
  • 設置頁眉
  • 忽略TLS證書錯誤

有沒有人有一個簡單的例子,如何實現這一目標?

我在API文檔HttpClient Class中發現了這個例子,但不清楚如何實現以上幾點。

回答

1

我花了幾個小時在看源代碼corefxgithub這個簡單的例子上來

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; 
     } 
    } 
} 

見代碼。