ASP.NET > http > httpClient




# 参考

### HttpClient
[HttpClientの類の使い方 - マイクロソフト系技術情報 Wiki](https://techinfoofmicrosofttech.osscons.jp/index.php?HttpClient%E3%81%AE%E9%A1%9E%E3%81%AE%E4%BD%BF%E3%81%84%E6%96%B9)
[開発者を苦しめる.NETのHttpClientのバグと紛らわしいドキュメント](https://www.infoq.com/jp/news/2016/09/HttpClient)

### jsonパース関係
[Json.NET (Newtonsoft.Json) の基本的な使い方 | @Subaru](https://netweblog.wordpress.com/2016/10/24/json-net-newtonsoft-json-usage/)
[Querying JSON with LINQ](https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm)

# httpClient



以下、IBMのlanguage-translatorを使うサンプルです

```csharp

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;


using Newtonsoft.Json.Linq;
using System.Net.Http.Formatting;

namespace FeedReader
{

    public class TransMessage
    {
        public string text { get; set; }
        public string source { get; set; }
        public string target { get; set; }
    }



    public class WatsonTranslator
    {

        private static HttpClient _httpClient = new HttpClient();
        private const string userName = "";
        private const string passWord = "";
        private const string url = "https://gateway.watsonplatform.net/language-translator/api/v2/translate";


        public async static Task<dynamic> Load()
        { 
            var msg = new TransMessage();
            msg.text = "Hello";
            msg.source = "en";
            msg.target = "ja";
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(msg);

            var result = await PostAsyncToWatson(json);
            return result;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public async static Task<string> PostAsyncToWatson(string json)
        {
            //送信オプション
            _httpClient.DefaultRequestHeaders.Clear();

            //認証方式をセット - Basic認証
            var userPass = System.Text.Encoding.ASCII.GetBytes($"{userName}:{passWord}");
            _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(userPass));

            //Accept（要求）方式をセット
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //content作成
            var content = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(json));
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            //Post送信
            var response = await _httpClient.PostAsync(url, content);

            //応答を取得しJsonに変換
            //var responseResult = await response.Content.ReadAsStringAsync();
            JObject jres = await response.Content.ReadAsAsync<JObject>(new[] { new JsonMediaTypeFormatter() });

            //translationsの情報をArrayで取得
            var jarr = jres["translations"] as JArray;
            var translation = jarr.First;

            //translationを取得
            var nameValue = translation["translation"] as JValue;
            var result = nameValue.Value as string;


            //応答
            return result;
        }


    }

}


```