2017-07-19 7 views
1

一部のWebサイト(URL)にHttp要求を送信し、応答を取得したい(基本的にGetAsyncとPutAsyncメソッドを使用する必要があります)、.NETCoreApp VS2017の1.1。.NETCoreApp 1.1を使用したHttpClientのサンプルアプリケーション

  • は、TLS証明書エラー
  • を無視し得ると
  • 設定ヘッダ
  • を投稿してください

は誰がどのようにこれを達成するために簡単な例を持っていますか?

この例はAPIドキュメントHttpClient Classにありますが、上記の点を達成する方法は不明です。

答えて

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のコードを参照してください。

関連する問題