HttpClient を使用して認証付きで投稿する方法 質問する

HttpClient を使用して認証付きで投稿する方法 質問する

私は、HttpClient を使用して C# で次の curl (私にとってはうまくいきます) を実行しようとしています。

curl -X POST http://www.somehosturl.com \
     -u <client-id>:<client-secret> \
     -d 'grant_type=password' \
     -d 'username=<email>' \
     -d 'password=<password>' \
     -d 'scope=all

C# コード:

HttpClientHandler handler = new HttpClientHandler { Credentials = new  
            System.Net.NetworkCredential ("my_client_id", "my_client_secret")
    };


    try
    {
        using(var httpClient = new HttpClient(handler))
        {
            var activationUrl = "www.somehosturl.com";

            var postData = "grant_type=password&[email protected]&password=mypass&scope=all";
            var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");

            var response = await httpClient.PostAsync(activationUrl, content);
            if(!response.IsSuccessStatusCode)
                return null;

            var result = await response.Content.ReadAsStringAsync();

            return result;
        }
    }
    catch(Exception)
    {
        return null;
    }

実行するとクラッシュし、例外もキャッチしません

通常、GET と POST は問題なく実行できますが、認証情報 (クライアント ID とクライアント シークレット) の設定方法がわかりません。

ベストアンサー1

まず、とAuthorizationを使用して -Headerを設定する必要があります。<clientid><clientsecret>

代わりに、以下のようにStringContent使用する必要があります。FormUrlEncodedContent

var client = new HttpClient();
client.BaseAddress = new Uri("http://myserver");
var request = new HttpRequestMessage(HttpMethod.Post, "/path");

var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
formData.Add(new KeyValuePair<string, string>("username", "<email>"));
formData.Add(new KeyValuePair<string, string>("password", "<password>"));
formData.Add(new KeyValuePair<string, string>("scope", "all"));

request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);

おすすめ記事